<?php

namespace App\Models;

use App\Observers\FeedObserver;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

#[ObservedBy([FeedObserver::class])]
class Feed extends Model implements HasMedia
{
    use HasFactory, InteractsWithMedia, SoftDeletes;

    protected $guarded = ['id'];

    protected function casts(): array
    {
        return [
            'stock' => 'integer',
            'price' => 'integer',
        ];
    }

    protected function formattedPrice(): Attribute
    {
        return Attribute::make(
            get: fn () => number_format($this->price, 0, ',', '.'),
        );
    }

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

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

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

    public function schedules(): BelongsToMany
    {
        return $this->belongsToMany(FeedSchedule::class, 'feed_feed_schedule')
            ->using(FeedFeedSchedule::class)
            ->withPivot('quantity')
            ->withTimestamps();
    }

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