#nullable enable
using System.Text.Json;
using Baya.Application.Contracts.Common;

namespace Baya.Infrastructure.CrossCutting.Seams.Real;

/// <summary>
/// Real <see cref="IIdentityKycProvider"/> over the Finnotech civil-registry (ثبت احوال) inquiry
/// (refinement-phase-8, 5.2). Selected by <c>Seams:IdentityKyc:Provider = finnotech</c>. Verifies the national
/// id is valid and returns the civil-registry full name used for the later credential cross-check.
///
/// <para><b>Liveness scope.</b> This MVP adapter performs the national-id + name inquiry (the deterministic KYC
/// gate). Photo/video liveness is a distinct vendor product; it is added by extending this same adapter to also
/// submit the <paramref name="livenessPayload"/> to the liveness endpoint and folding its verdict into
/// <see cref="IdentityKycResult.Passed"/> — the seam contract does not change.</para>
/// </summary>
public sealed class FinnotechIdentityKycProvider(FinnotechClient client) : IIdentityKycProvider
{
    public async Task<IdentityKycResult> VerifyAsync(string nationalId, string? livenessPayload, CancellationToken cancellationToken = default)
    {
        var trackId = FinnotechClient.NewTrackId();
        var vendorRef = $"FINNOTECH-KYC-{trackId}";
        var path = $"kyc/v2/clients/{client.ClientId}/nidVerification" +
                   $"?nationalCode={Uri.EscapeDataString(nationalId)}&trackId={trackId}";

        var (document, raw) = await client.GetAsync(path, cancellationToken);
        using var _ = document;

        var root = document.RootElement;
        var passed = root.TryGetProperty("result", out var result)
                     && result.TryGetProperty("nidVerified", out var verified)
                     && verified.ValueKind == JsonValueKind.True;

        string? matchedName = null;
        if (passed && result.TryGetProperty("fullName", out var fullName) && fullName.ValueKind == JsonValueKind.String)
            matchedName = fullName.GetString();

        return new IdentityKycResult(
            Passed: passed,
            MatchedName: matchedName,
            VendorRef: vendorRef,
            ExternalResponseJson: raw,
            FailureReason: passed ? null : "Identity could not be verified against the civil registry.");
    }
}
