<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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;
    }
}
