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

class DberpDepartment extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_departments';

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

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

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

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

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

    /**
     * @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 manager(): BelongsTo
    {
        return $this->belongsTo(DberpEmployee::class, 'manager_employee_id');
    }

    public function positions(): HasMany
    {
        return $this->hasMany(DberpPosition::class, 'department_id');
    }

    /**
     * 返回所有下级部门 id（不含自身），用于维护上级部门选择范围，避免形成环状层级。
     *
     * @return list<int>
     */
    public function getDescendantIds(): array
    {
        $out = [];
        $stack = $this->children()->pluck('id')->map(fn (mixed $id): int => (int) $id)->all();

        while ($stack !== []) {
            $id = array_pop($stack);
            $out[] = $id;

            foreach (static::query()->where('parent_id', $id)->pluck('id') as $childId) {
                $stack[] = (int) $childId;
            }
        }

        return $out;
    }

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