<?php

declare(strict_types=1);

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

namespace App\Services\SupportCenter;

use App\Support\DberpProductVersion;
use Illuminate\Http\Request;

/**
 * 构建 Support Center well-known 站点校验 JSON（不含密钥与内部枚举）。
 */
final class HostSiteVerificationResponseBuilder
{
    private const PROTOCOL_VERSION = '1';

    public function __construct(
        private readonly HostInstanceIdentityService $instanceIdentityService,
        private readonly HostSiteConnectionStatusResolver $connectionStatusResolver,
        private readonly DberpProductVersion $productVersion,
    ) {}

    /**
     * @return array<string, string>
     */
    public function buildForPublication(?string $domainHost = null): array
    {
        return $this->buildPayload($this->resolveDomainHost($domainHost, null));
    }

    /**
     * @return array<string, string>
     */
    public function build(Request $request): array
    {
        return $this->buildPayload($this->resolveDomain($request));
    }

    /**
     * @return array<string, string>
     */
    private function buildPayload(string $domain): array
    {
        $this->instanceIdentityService->ensureProvisioned();

        $payload = [
            'product' => $this->productCode(),
            'protocol_version' => self::PROTOCOL_VERSION,
            'domain' => $domain,
            'instance_id' => $this->instanceIdentityService->instanceId(),
            'identity_status' => $this->instanceIdentityService->identityStatus()->value,
            'host_version' => $this->productVersion->displayVersion(),
            'site_connection_status' => $this->connectionStatusResolver->resolve()->value,
            'timestamp' => now()->utc()->toIso8601String(),
        ];

        if ((bool) config('dberp.support_center.debug_open_host_meta', false)) {
            $payload['debug_host_meta'] = json_encode([
                'use_stub' => (bool) config('dberp.support_center.use_stub', true),
                'has_validation_base_url' => $this->filledConfigString('dberp.support_center.validation_base_url'),
            ], JSON_THROW_ON_ERROR);
        }

        return $payload;
    }

    private function productCode(): string
    {
        $code = config('dberp.support_center.product_code', 'dberp');

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

        return trim($code);
    }

    private function resolveDomain(Request $request): string
    {
        return $this->resolveDomainHost(null, $request);
    }

    private function resolveDomainHost(?string $domainHost, ?Request $request): string
    {
        if (is_string($domainHost) && trim($domainHost) !== '') {
            return trim($domainHost);
        }

        $validationBaseUrl = config('dberp.support_center.validation_base_url');

        if (is_string($validationBaseUrl) && trim($validationBaseUrl) !== '') {
            $host = parse_url($validationBaseUrl, PHP_URL_HOST);

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

        $appUrl = config('app.url');

        if (is_string($appUrl) && trim($appUrl) !== '') {
            $host = parse_url($appUrl, PHP_URL_HOST);

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

        if ($request instanceof Request) {
            return $request->getHost();
        }

        return 'localhost';
    }

    private function filledConfigString(string $key): bool
    {
        $value = config($key);

        return is_string($value) && trim($value) !== '';
    }
}
