<?php

namespace App\Models;

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

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

    protected $guarded = ['id'];

    protected function casts(): array
    {
        return [
            'purchase_date' => 'date',
            'total_price' => 'integer',
        ];
    }

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

    public function updateFeedStock(): void
    {
        foreach ($this->items as $item) {
            $feed = $item->feed;
            if ($feed) {
                $feed->increment('stock', $item->quantity);
            }
        }
    }

    public function revertFeedStock(): void
    {
        foreach ($this->items as $item) {
            $feed = $item->feed;
            if ($feed) {
                $feed->decrement('stock', $item->quantity);
            }
        }
    }
}
