<?php

namespace App\Models;

use App\Observers\EggCollectionObserver;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

#[ObservedBy(EggCollectionObserver::class)]
class EggCollection extends Model
{
    use HasFactory, SoftDeletes;

    protected $guarded = ['id'];

    public function items(): HasMany
    {
        return $this->hasMany(EggCollectionItem::class);
    }

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

    public function syncTotals()
    {
        $this->total_eggs = $this->items()->where('is_broken', false)->sum('quantity');
        $this->total_broken_eggs = $this->items()->where('is_broken', true)->sum('quantity');
        $this->saveQuietly();
    }

    protected function casts(): array
    {
        return [
            'production_date' => 'datetime',
            'total_eggs' => 'decimal:2',
            'total_broken_eggs' => 'decimal:2',
        ];
    }
}
