<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class FatteningLotAnimal extends Model
{
    use HasFactory;

    protected $fillable = [
        'fattening_lot_id',
        'cattle_id',
        'entry_weight_kg',
        'entry_date',
        'exit_weight_kg',
        'exit_date',
        'removed_at',
    ];

    protected $casts = [
        'entry_date' => 'date',
        'exit_date' => 'date',
        'removed_at' => 'date',
        'entry_weight_kg' => 'decimal:2',
        'exit_weight_kg' => 'decimal:2',
    ];

    public function fatteningLot(): BelongsTo
    {
        return $this->belongsTo(FatteningLot::class);
    }

    public function cattle(): BelongsTo
    {
        return $this->belongsTo(Cattle::class);
    }

    public function daysInLot(): int
    {
        $end = $this->exit_date ?? $this->removed_at ?? Carbon::today();

        return max(0, $this->entry_date->diffInDays($end));
    }

    public function weightGainKg(): ?float
    {
        if ($this->exit_weight_kg === null) {
            return null;
        }

        return (float) $this->exit_weight_kg - (float) $this->entry_weight_kg;
    }
}
