<?php

declare(strict_types=1);

namespace App\Support;

use App\Business\Purchase\Enums\PurchaseRequestSourceType;
use App\Business\Sales\Enums\SalesSourceType;
use App\Models\DberpDictionaryItem;
use App\Models\DberpSystemProfile;
use BackedEnum;

/**
 * 业务控制参数中的默认值，供新建单据表单与解析逻辑统一读取。
 */
final class DberpSystemProfileBusinessDefaults
{
    public static function defaultSourceTypeItemId(): ?int
    {
        return once(function (): ?int {
            $id = self::profile()?->default_source_type_item_id;

            return $id === null ? null : (int) $id;
        });
    }

    public static function defaultSalesSourceType(): string
    {
        return self::resolveBackedEnumDefault(SalesSourceType::class, SalesSourceType::Manual->value);
    }

    public static function defaultPurchaseRequestSourceType(): string
    {
        return self::resolveBackedEnumDefault(PurchaseRequestSourceType::class, PurchaseRequestSourceType::Manual->value);
    }

    /**
     * @param  class-string<BackedEnum>  $enumClass
     */
    private static function resolveBackedEnumDefault(string $enumClass, string $fallback): string
    {
        $itemId = self::defaultSourceTypeItemId();

        if ($itemId === null) {
            return $fallback;
        }

        $code = DberpDictionaryItem::query()->whereKey($itemId)->value('code');

        if (! is_string($code) || $code === '') {
            return $fallback;
        }

        foreach ($enumClass::cases() as $case) {
            if ($case instanceof BackedEnum && $case->value === $code) {
                return (string) $case->value;
            }
        }

        return $fallback;
    }

    private static function profile(): ?DberpSystemProfile
    {
        return once(function (): ?DberpSystemProfile {
            return DberpSystemProfile::query()->first([
                'id',
                'default_source_type_item_id',
            ]);
        });
    }
}
