<?php

namespace App\Services;

use App\Models\FatteningLot;
use Carbon\Carbon;

class FatteningLotPastureCostService
{
    public function accruedCost(FatteningLot $lot, ?Carbon $asOf = null): float
    {
        $asOf ??= Carbon::today();
        $end = $lot->status === FatteningLot::STATUS_CLOSED && $lot->closed_at
            ? $lot->closed_at
            : $asOf;

        if ($end->lessThan($lot->pastureAccrualStartDate())) {
            return 0.0;
        }

        $days = max(1, $lot->pastureAccrualStartDate()->diffInDays($end) + 1);
        $months = $days / 30.0;
        $heads = max(1, $lot->animals()->count());
        $monthly = $lot->pastureCostPerAnimalMonth();

        return round($months * $monthly * $heads, 2);
    }

    public function projectedTotal(FatteningLot $lot): float
    {
        return $this->accruedCost($lot, $lot->plannedExitDate());
    }
}
