<?php

declare(strict_types=1);

namespace App\Support;

/**
 * 业务字典项维护策略：按字典类型编码区分「系统固定」与「业务可维护」。
 *
 * 未在配置中显式列入「业务可维护」的类型，默认按系统固定处理，避免插件新增类型被误放开权限。
 */
final class DberpDictionaryItemMaintenance
{
    public const STRATEGY_SYSTEM_FIXED = 'system_fixed';

    public const STRATEGY_BUSINESS_MAINTAINABLE = 'business_maintainable';

    /**
     * @return value-of<self::STRATEGY_*>
     */
    public static function strategyForTypeCode(?string $typeCode): string
    {
        if ($typeCode === null || $typeCode === '') {
            return self::STRATEGY_SYSTEM_FIXED;
        }

        $business = self::businessMaintainableTypeCodes();

        if (in_array($typeCode, $business, true)) {
            return self::STRATEGY_BUSINESS_MAINTAINABLE;
        }

        $system = self::systemFixedTypeCodes();

        if (in_array($typeCode, $system, true)) {
            return self::STRATEGY_SYSTEM_FIXED;
        }

        return self::STRATEGY_SYSTEM_FIXED;
    }

    public static function isSystemFixedForTypeCode(?string $typeCode): bool
    {
        return self::strategyForTypeCode($typeCode) === self::STRATEGY_SYSTEM_FIXED;
    }

    public static function isBusinessMaintainableForTypeCode(?string $typeCode): bool
    {
        return self::strategyForTypeCode($typeCode) === self::STRATEGY_BUSINESS_MAINTAINABLE;
    }

    /**
     * @return list<string>
     */
    private static function systemFixedTypeCodes(): array
    {
        $configured = config('dberp.dictionary.type_item_maintenance.system_fixed_type_codes');

        return is_array($configured) ? array_values(array_filter(array_map('strval', $configured))) : [];
    }

    /**
     * @return list<string>
     */
    private static function businessMaintainableTypeCodes(): array
    {
        $configured = config('dberp.dictionary.type_item_maintenance.business_maintainable_type_codes');

        return is_array($configured) ? array_values(array_filter(array_map('strval', $configured))) : [];
    }
}
