<?php

declare(strict_types=1);

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;
    }
}
