<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class FinalShipment extends Model
{
    use HasFactory;

    protected $fillable = [
        'shipment_id',
        'original_quantity',
        'adjusted_quantity',
        'final_quantity',
        'adjustment_reason',
        'final_shipment_date',
        'final_invoice_path',
        'final_packing_list_path',
        'inspection_remarks',
        'status',
        'created_by'
    ];

    protected $casts = [
        'final_shipment_date' => 'date',
    ];

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

        static::creating(function ($finalShipment) {
            $finalShipment->final_quantity = $finalShipment->original_quantity + $finalShipment->adjusted_quantity;
        });

        static::updating(function ($finalShipment) {
            $finalShipment->final_quantity = $finalShipment->original_quantity + $finalShipment->adjusted_quantity;
        });
    }

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

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

    public function getStatusBadgeColorAttribute(): string
    {
        return match($this->status) {
            'pending' => 'warning',
            'adjusted' => 'primary',
            'completed' => 'success',
            default => 'secondary',
        };
    }

    public function getAdjustmentTypeAttribute(): string
    {
        return $this->adjusted_quantity >= 0 ? 'positive' : 'negative';
    }
}