<?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\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DberpPosition extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_positions';

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

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

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

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

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

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

    public function department(): BelongsTo
    {
        return $this->belongsTo(DberpDepartment::class, 'department_id');
    }

    public function scopeEnabled(Builder $query): Builder
    {
        return $query->where('is_enabled', true);
    }
}
