<?php

declare(strict_types=1);

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

namespace App\Services\Plugin;

use App\Models\HostSystemAuthorization;
use App\Services\SupportCenter\HostSiteOnboardingStatusCacheStore;

/**
 * 解析插件 Open Host 请求所需的站点与授权上下文。
 */
final class HostPluginSupportCenterContextResolver
{
    public function __construct(
        private readonly HostSiteOnboardingStatusCacheStore $siteStatusCacheStore,
    ) {}

    public function resolveSiteNo(): ?string
    {
        $authorization = HostSystemAuthorization::singleton();
        $fromSnapshot = $this->nullableString($authorization->site_no);

        if ($fromSnapshot !== null) {
            return $fromSnapshot;
        }

        $configured = config('dberp.support_center.site_no');

        if (is_string($configured) && trim($configured) !== '') {
            return trim($configured);
        }

        $cached = $this->siteStatusCacheStore->get();
        $siteNo = is_array($cached) ? ($cached['site_no'] ?? null) : null;

        return is_string($siteNo) && trim($siteNo) !== '' ? trim($siteNo) : null;
    }

    public function resolveLicenseNo(): ?string
    {
        $authorization = HostSystemAuthorization::singleton();
        $fromSnapshot = $this->nullableString($authorization->license_no);

        if ($fromSnapshot !== null) {
            return $fromSnapshot;
        }

        $configured = config('dberp.support_center.license_no');

        if (is_string($configured) && trim($configured) !== '') {
            return trim($configured);
        }

        $cached = $this->siteStatusCacheStore->get();

        if (! is_array($cached)) {
            return null;
        }

        $data = $cached['data'] ?? null;

        if (! is_array($data)) {
            return null;
        }

        $licenseNo = $data['license_no'] ?? null;

        return is_string($licenseNo) && trim($licenseNo) !== '' ? trim($licenseNo) : null;
    }

    private function nullableString(mixed $value): ?string
    {
        if (! is_string($value)) {
            return null;
        }

        $trimmed = trim($value);

        return $trimmed === '' ? null : $trimmed;
    }
}
