<?php

declare(strict_types=1);

namespace App\Models;

use App\Business\Inventory\Enums\TransferDocumentStatus;
use App\Models\Concerns\GeneratesDberpCode;
use App\Models\Concerns\HasDberpAuditTrail;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Validation\ValidationException;

class DberpTransferOrder extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_transfer_orders';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'from_warehouse_id',
        'from_warehouse_contact_phone_snapshot',
        'from_warehouse_country_code_snapshot',
        'from_warehouse_region_name_snapshot',
        'from_warehouse_address_snapshot',
        'to_warehouse_id',
        'to_warehouse_contact_phone_snapshot',
        'to_warehouse_country_code_snapshot',
        'to_warehouse_region_name_snapshot',
        'to_warehouse_address_snapshot',
        'reason',
        'status',
        'business_time',
        'effective_at',
        'completed_at',
        'voided_at',
        'remark',
    ];

    protected static function booted(): void
    {
        static::deleting(function (self $order): void {
            if ($order->status !== TransferDocumentStatus::Draft->value) {
                throw ValidationException::withMessages([
                    'status' => __('dberp.errors.inventory_delete_only_draft'),
                ]);
            }
        });
    }

    protected function casts(): array
    {
        return [
            'from_warehouse_id' => 'integer',
            'to_warehouse_id' => 'integer',
            'business_time' => 'datetime',
            'effective_at' => 'datetime',
            'completed_at' => 'datetime',
            'voided_at' => 'datetime',
        ];
    }

    public function getDberpNumberScope(): string
    {
        return 'transfer_order';
    }

    public function getDberpAuditActionPrefix(): string
    {
        return 'dberp.transfer_order';
    }

    /**
     * @return list<string>
     */
    public function getDberpAuditFields(): array
    {
        return $this->getFillable();
    }

    public function fromWarehouse(): BelongsTo
    {
        return $this->belongsTo(DberpWarehouse::class, 'from_warehouse_id');
    }

    public function toWarehouse(): BelongsTo
    {
        return $this->belongsTo(DberpWarehouse::class, 'to_warehouse_id');
    }

    public function items(): HasMany
    {
        return $this->hasMany(DberpTransferOrderItem::class, 'order_id');
    }
}