<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class HarvestRecord extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'farm_id', 'pond_id', 'cycle_id', 'harvest_date', 'total_fish_harvested',
        'total_weight_kg', 'total_mortality_count', 'harvest_type', 'harvest_notes', 'logged_by',
    ];

    protected function casts(): array
    {
        return [
            'harvest_date' => 'date',
            'total_weight_kg' => 'decimal:2',
        ];
    }

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

    public function cycle(): BelongsTo
    {
        return $this->belongsTo(ProductionCycle::class, 'cycle_id');
    }

    public function logger(): BelongsTo
    {
        return $this->belongsTo(User::class, 'logged_by');
    }

    public function salesRecords(): HasMany
    {
        return $this->hasMany(SalesRecord::class, 'harvest_id');
    }

    public function getAvgWeightGAttribute(): float
    {
        if (! $this->total_fish_harvested) {
            return 0;
        }

        return (float) $this->total_weight_kg * 1000 / $this->total_fish_harvested;
    }

    public function getTotalRevenueAttribute(): float
    {
        return (float) $this->salesRecords()->sum('total_amount_naira');
    }
}
