#nullable enable
using System.Net.Http.Headers;
using System.Text.Json;
using Microsoft.Extensions.Options;

namespace Baya.Infrastructure.CrossCutting.Seams.Real;

/// <summary>
/// Thin shared client for the Finnotech-class KYC bridge that fronts three trust rails (شاهکار / e-KYC /
/// استعلام شبا). Owns the base address, the bearer-token authentication, and a per-call <c>trackId</c> — the
/// three seam adapters differ only in the resource path + response mapping. Credentials come from
/// <c>Seams:Finnotech</c>; a deployment supplies a current access token (the client-credential token exchange is
/// a deploy-time concern, out of the MVP adapter's scope).
/// </summary>
public sealed class FinnotechClient(HttpClient httpClient, IOptions<SeamOptions> options)
{
    private const string DefaultBaseUrl = "https://apibeta.finnotech.ir";
    private readonly FinnotechOptions _options = options.Value.Finnotech;

    public string ClientId => _options.ClientId;

    /// <summary>A fresh, unique inquiry track id (Finnotech requires one per call; kept for audit).</summary>
    public static string NewTrackId() => Guid.NewGuid().ToString("N");

    /// <summary>Issues an authenticated GET and returns the parsed body + the raw JSON (persisted as
    /// <c>external_response_json</c>). The base URL defaults to Finnotech's host when unset.</summary>
    public async Task<(JsonDocument Document, string Raw)> GetAsync(string relativePath, CancellationToken cancellationToken)
    {
        var baseUrl = string.IsNullOrWhiteSpace(_options.BaseUrl) ? DefaultBaseUrl : _options.BaseUrl.TrimEnd('/');
        using var request = new HttpRequestMessage(HttpMethod.Get, $"{baseUrl}/{relativePath.TrimStart('/')}");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _options.AccessToken);

        using var response = await httpClient.SendAsync(request, cancellationToken);
        var raw = await response.Content.ReadAsStringAsync(cancellationToken);
        response.EnsureSuccessStatusCode();

        return (JsonDocument.Parse(raw), raw);
    }
}
