<?php

namespace App\Services;

use App\Models\Cattle;
use App\Models\WeightRecord;
use Carbon\Carbon;

class WeightRecordService
{
    public function record(Cattle $cattle, float $weightKg, Carbon $weighedAt, ?string $notes, ?int $userId): WeightRecord
    {
        $previous = WeightRecord::query()
            ->where('cattle_id', $cattle->id)
            ->where('weighed_at', '<', $weighedAt->toDateString())
            ->orderByDesc('weighed_at')
            ->first();

        $weightGain = null;
        $daysSince = null;
        $dailyGain = null;

        if ($previous) {
            $weightGain = round($weightKg - (float) $previous->weight_kg, 2);
            $daysSince = max(1, $previous->weighed_at->diffInDays($weighedAt));
            $dailyGain = round($weightGain / $daysSince, 4);
        }

        return WeightRecord::create([
            'cattle_id' => $cattle->id,
            'weight_kg' => $weightKg,
            'weighed_at' => $weighedAt,
            'weight_gain_kg' => $weightGain,
            'days_since_last' => $daysSince,
            'daily_weight_gain' => $dailyGain,
            'notes' => $notes,
            'user_id' => $userId,
        ]);
    }
}
