<?php

declare(strict_types=1);

namespace App\Models;

use App\Business\MasterData\MasterDataDeleteGuard;
use App\Models\Concerns\GeneratesDberpBrandCode;
use App\Models\Concerns\HasDberpAuditTrail;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class DberpProductBrand extends Model
{
    use GeneratesDberpBrandCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_product_brands';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'brand_code',
        'name',
        'short_name',
        'logo',
        'description',
        'is_enabled',
        'sort_order',
    ];

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

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

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

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

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

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

    public static function formatOptionLabel(self $brand): string
    {
        return sprintf('%s（%s）', $brand->name, $brand->brand_code);
    }

    /**
     * 商品表单下拉：默认可选启用品牌；编辑时可额外保留当前已选中的停用品牌。
     *
     * @return array<int, string>
     */
    public static function optionsForProductForm(?int $preserveDisabledBrandId): array
    {
        $out = [];

        foreach (static::query()->where('is_enabled', true)->orderBy('sort_order')->orderBy('id')->cursor() as $brand) {
            $out[(int) $brand->getKey()] = static::formatOptionLabel($brand);
        }

        if ($preserveDisabledBrandId !== null) {
            $extra = static::query()->find($preserveDisabledBrandId);
            if ($extra !== null && ! $extra->is_enabled) {
                $out[(int) $extra->getKey()] = static::formatOptionLabel($extra);
            }
        }

        return $out;
    }
}
