<?php

declare(strict_types=1);

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

namespace App\Services\SupportCenter;

/**
 * 从官方发布包注入的 Open Host 凭证文件读取连接参数（文件不得提交到源码仓库）。
 */
final class SupportCenterReleaseCredentialProvider
{
    /**
     * @return array{base_url: string, host_token: string, host_key: ?string}|null
     */
    public function read(): ?array
    {
        $path = $this->credentialsFilePath();

        if ($path === null || ! is_file($path) || ! is_readable($path)) {
            return null;
        }

        try {
            $raw = file_get_contents($path);
        } catch (\Throwable) {
            return null;
        }

        if (! is_string($raw) || trim($raw) === '') {
            return null;
        }

        try {
            $decoded = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
        } catch (\Throwable) {
            return null;
        }

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

        return $this->normalizePayload($decoded);
    }

    public function credentialsFileExists(): bool
    {
        $path = $this->credentialsFilePath();

        return $path !== null && is_file($path);
    }

    public function credentialsFilePath(): ?string
    {
        $configured = config('dberp.support_center.release_credentials_path');

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

        return trim($configured);
    }

    /**
     * @param  array<string, mixed>  $payload
     * @return array{base_url: string, host_token: string, host_key: ?string}|null
     */
    private function normalizePayload(array $payload): ?array
    {
        $baseUrl = $this->nonEmptyString($payload['base_url'] ?? null);

        $hostToken = $this->nonEmptyString($payload['host_token'] ?? null);

        if ($baseUrl === null || $hostToken === null) {
            return null;
        }

        if ($this->isPlaceholderValue($hostToken) || $this->isPlaceholderValue($baseUrl)) {
            return null;
        }

        $hostKey = $this->nonEmptyString($payload['host_key'] ?? null);

        return [
            'base_url' => $baseUrl,
            'host_token' => $hostToken,
            'host_key' => $hostKey,
        ];
    }

    private function isPlaceholderValue(string $value): bool
    {
        $normalized = strtolower(trim($value));

        foreach ([
            'replace_at_release_time',
            'your_host_token_here',
            'your-token-here',
            'changeme',
            'example.com',
        ] as $placeholder) {
            if ($normalized === $placeholder || str_contains($normalized, 'replace_at_release')) {
                return true;
            }
        }

        return false;
    }

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

        $trimmed = trim($value);

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