<?php

declare(strict_types=1);

namespace App\Models;

use App\Business\MasterData\MasterDataDeleteGuard;
use App\Models\Concerns\GeneratesDberpCode;
use App\Models\Concerns\HasDberpAuditTrail;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DberpWarehouse extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_warehouses';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'name',
        'warehouse_type',
        'address',
        'country_code',
        'region_id',
        'region_name_snapshot',
        'manager_employee_id',
        'contact_phone',
        'is_default',
        'is_enabled',
        'sort_order',
        'remark',
    ];

    protected static function booted(): void
    {
        static::deleting(function (self $warehouse): void {
            app(MasterDataDeleteGuard::class)->ensureCanDelete($warehouse);
        });

        static::saved(function (self $warehouse): void {
            if (! $warehouse->is_default) {
                return;
            }

            self::query()
                ->whereKeyNot($warehouse->getKey())
                ->where('is_default', true)
                ->update([
                    'is_default' => false,
                    'updated_at' => now(),
                ]);
        });
    }

    protected function casts(): array
    {
        return [
            'region_id' => 'integer',
            'manager_employee_id' => 'integer',
            'is_default' => 'boolean',
            'is_enabled' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

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

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

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

    public function manager(): BelongsTo
    {
        return $this->belongsTo(DberpEmployee::class, 'manager_employee_id');
    }

    public function region(): BelongsTo
    {
        return $this->belongsTo(DberpRegion::class, 'region_id');
    }
}