<?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\HasMany;

class DberpUnit extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_units';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'name',
        'sort_order',
        'is_enabled',
        'remark',
    ];

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

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

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

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

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

    public function products(): HasMany
    {
        return $this->hasMany(DberpProduct::class, 'unit_id');
    }

    public function productsUsingAsAuxiliaryUnit(): HasMany
    {
        return $this->hasMany(DberpProduct::class, 'auxiliary_unit_id');
    }

    public function productSkus(): HasMany
    {
        return $this->hasMany(DberpProductSku::class, 'unit_id');
    }
}
