<?php

declare(strict_types=1);

namespace App\Models;

use App\Business\MasterData\MasterDataDeleteGuard;
use App\Models\Concerns\GeneratesDberpCode;
use App\Models\Concerns\HasDberpAuditTrail;
use App\Services\DberpAuditService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Auth;

class DberpCustomerCategory extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_customer_categories';

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

    /**
     * @var array<string, mixed>
     */
    protected $attributes = [
        'status' => 'active',
        'sort' => 0,
    ];

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

        static::updated(function (self $category): void {
            if (! Auth::check()) {
                return;
            }

            if (! $category->wasChanged('status')) {
                return;
            }

            if ($category->getOriginal('status') !== 'active' || $category->status !== 'inactive') {
                return;
            }

            app(DberpAuditService::class)->log(
                $category->getDberpAuditActionPrefix().'.disabled',
                $category,
                ['status' => (string) $category->getOriginal('status')],
                ['status' => (string) $category->status],
            );
        });
    }

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

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

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

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

    public function customers(): HasMany
    {
        return $this->hasMany(DberpCustomer::class, 'customer_category_id');
    }

    /**
     * 客户主档表单：分类下拉（默认可选启用分类；编辑时可保留当前已选停用分类）。
     *
     * @return array<int, string>
     */
    public static function optionsForCustomerMasterForm(?int $preserveInactiveCategoryId): array
    {
        $out = [];

        foreach (static::query()->where('status', 'active')->orderBy('sort')->orderByDesc('id')->cursor() as $category) {
            $out[(int) $category->getKey()] = (string) $category->name;
        }

        if ($preserveInactiveCategoryId !== null) {
            $extra = static::query()->find($preserveInactiveCategoryId);
            if ($extra !== null && $extra->status !== 'active') {
                $out[(int) $extra->getKey()] = sprintf('%s（%s）', $extra->name, __('dberp.labels.master_disabled_suffix'));
            }
        }

        return $out;
    }
}
