<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use Illuminate\Support\Facades\File;

/**
 * 将站点校验 JSON 写入 public/.well-known，供 Web 服务器按静态文件直接返回 HTTP 200。
 *
 * 避免部分 Nginx（如宝塔 error_page 404 → index.php）在走 PHP 时仍对外保留 404 状态码。
 */
final class HostSiteVerificationStaticPublisher
{
    public const PUBLIC_RELATIVE_PATH = '.well-known/dberp-site-verification.json';

    public function __construct(
        private readonly HostSiteVerificationResponseBuilder $responseBuilder,
    ) {}

    public function absolutePath(): string
    {
        return public_path(self::PUBLIC_RELATIVE_PATH);
    }

    public function isPublished(): bool
    {
        return is_file($this->absolutePath()) && is_readable($this->absolutePath());
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function publishFromPayload(array $payload): bool
    {
        $directory = dirname($this->absolutePath());

        if (! File::isDirectory($directory)) {
            File::makeDirectory($directory, 0755, true);
        }

        $json = json_encode(
            $payload,
            JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
        );

        return File::put($this->absolutePath(), $json) !== false;
    }

    public function publish(?string $domainHost = null): bool
    {
        return $this->publishFromPayload(
            $this->responseBuilder->buildForPublication($domainHost),
        );
    }

    public function publishIfAbsent(?string $domainHost = null): bool
    {
        if ($this->isPublished()) {
            return true;
        }

        return $this->publish($domainHost);
    }

    public function publishFromSystemUrl(?string $systemUrl): bool
    {
        $host = is_string($systemUrl) ? parse_url($systemUrl, PHP_URL_HOST) : false;

        return $this->publish(is_string($host) && $host !== '' ? $host : null);
    }
}
