<?php

namespace App\Services\Wallet;

use App\Models\Player;
use Illuminate\Support\Facades\Http;
use App\Services\Integration\PartnerSiteConfigResolver;
use App\Support\Integration\WalletApiUrlSanitizer;

/** 按幂等键查询主站钱包侧是否已有对应划转记录。 */
final class HttpMainSiteWalletIdempotentProbeClient
{
    public function __construct(
        private readonly PartnerSiteConfigResolver $partnerSiteConfigResolver,
    ) {}

    public function probe(Player $player, string $idempotentKey): MainSiteWalletIdempotentProbeResult
    {
        $idempotentKey = trim($idempotentKey);
        if ($idempotentKey === '') {
            return new MainSiteWalletIdempotentProbeResult(
                status: MainSiteWalletIdempotentProbeResult::STATUS_SKIPPED,
                message: 'empty_idempotent_key',
            );
        }

        $config = $this->partnerSiteConfigResolver->resolveForPlayer($player);
        if (! $config->enabled || ! $config->hasWalletApi()) {
            return new MainSiteWalletIdempotentProbeResult(
                status: MainSiteWalletIdempotentProbeResult::STATUS_SKIPPED,
                message: 'wallet_api_not_configured',
            );
        }

        $base = WalletApiUrlSanitizer::normalizeAndValidate($config->walletApiUrl);
        if ($base === null) {
            return new MainSiteWalletIdempotentProbeResult(
                status: MainSiteWalletIdempotentProbeResult::STATUS_UNAVAILABLE,
                message: 'wallet_api_url_invalid',
            );
        }

        $path = $config->walletLookupIdempotentPath;
        $url = $base.'/'.ltrim($path, '/');
        $headers = ['Accept' => 'application/json'];
        if (is_string($config->walletApiKey) && $config->walletApiKey !== '') {
            $headers['Authorization'] = 'Bearer '.$config->walletApiKey;
        }

        $query = [
            'site_code' => $player->site_code,
            'site_player_id' => $player->site_player_id,
            'idempotent_key' => $idempotentKey,
        ];

        try {
            $response = Http::withHeaders($headers)
                ->timeout($config->walletTimeoutSeconds)
                ->acceptJson()
                ->get($url, $query);
        } catch (\Throwable $e) {
            return new MainSiteWalletIdempotentProbeResult(
                status: MainSiteWalletIdempotentProbeResult::STATUS_UNAVAILABLE,
                message: $e->getMessage(),
            );
        }

        $payload = $response->json();
        if (! $response->successful() || ! is_array($payload)) {
            $message = is_array($payload) && is_string($payload['message'] ?? null)
                ? (string) $payload['message']
                : 'HTTP '.$response->status();

            return new MainSiteWalletIdempotentProbeResult(
                status: MainSiteWalletIdempotentProbeResult::STATUS_UNAVAILABLE,
                message: $message,
            );
        }

        $data = data_get($payload, 'data');
        if (! is_array($data)) {
            return new MainSiteWalletIdempotentProbeResult(
                status: MainSiteWalletIdempotentProbeResult::STATUS_UNAVAILABLE,
                message: 'invalid_response',
            );
        }

        $found = (bool) ($data['found'] ?? false);
        if (! $found) {
            return new MainSiteWalletIdempotentProbeResult(
                status: MainSiteWalletIdempotentProbeResult::STATUS_NOT_FOUND,
                found: false,
                success: null,
            );
        }

        $success = (bool) ($data['success'] ?? false);

        return new MainSiteWalletIdempotentProbeResult(
            status: $success
                ? MainSiteWalletIdempotentProbeResult::STATUS_MATCHED
                : MainSiteWalletIdempotentProbeResult::STATUS_FAILED,
            found: true,
            success: $success,
            externalRefNo: is_string($data['external_ref_no'] ?? null) ? $data['external_ref_no'] : null,
            operation: is_string($data['operation'] ?? null) ? $data['operation'] : null,
        );
    }
}
