<?php

namespace App\Models\Supplier;

use App\Models\Agency\Agency;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class SupplierPriceList extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'supplier_price_lists';

    protected $fillable = [
        'agency_id',
        'supplier_id',
        'name',
        'season_start',
        'season_end',
        'marketplace_id',
        'is_active',
        'notes',
        'created_by',
        'updated_by',
    ];

    protected function casts(): array
    {
        return [
            'season_start' => 'date',
            'season_end' => 'date',
            'is_active' => 'boolean',
        ];
    }

    // Relationships
    public function agency()
    {
        return $this->belongsTo(Agency::class);
    }

    public function supplier()
    {
        return $this->belongsTo(Supplier::class);
    }

    public function marketplace()
    {
        return $this->belongsTo(\App\Models\Agency\Marketplace::class, 'marketplace_id');
    }

    public function items()
    {
        return $this->hasMany(SupplierPriceItem::class, 'price_list_id');
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    protected static function boot(): void
    {
        parent::boot();

        static::creating(function (SupplierPriceList $list) {
            if (auth()->check()) {
                $list->created_by = auth()->id();
            }
        });

        static::updating(function (SupplierPriceList $list) {
            if (auth()->check()) {
                $list->updated_by = auth()->id();
            }
        });
    }
}
