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

class DberpProductCategory extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_product_categories';

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

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

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

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

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

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

    public function parent(): BelongsTo
    {
        return $this->belongsTo(self::class, 'parent_id');
    }

    public function children(): HasMany
    {
        return $this->hasMany(self::class, 'parent_id');
    }

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