#nullable enable
using Baya.Application.Contracts.Common;

namespace Baya.Infrastructure.CrossCutting.Seams.Real;

/// <summary>
/// Real <see cref="IShahkarVerifier"/> over the Finnotech شاهکار phone↔national-id inquiry (refinement-phase-8,
/// 5.2). Selected by <c>Seams:Shahkar:Provider = finnotech</c>. Maps the vendor's boolean match to
/// <see cref="ShahkarMatchResult"/> and persists the raw response for audit.
///
/// <para><b>Shared-SIM is a handled state, not derivable from Shahkar alone.</b> The شاهکار registry only asserts
/// whether the SIM is bound to the national id — it does not distinguish "owned by a family member" from a plain
/// mismatch. So a real no-match is reported as a plain mismatch (<c>IsSharedSim = false</c>) with a non-accusatory
/// reason; the explicit shared-SIM branch stays reachable through the mock (and any future vendor that surfaces
/// the ownership relationship). The handler's downstream behaviour is unchanged either way.</para>
/// </summary>
public sealed class FinnotechShahkarVerifier(FinnotechClient client) : IShahkarVerifier
{
    public async Task<ShahkarMatchResult> MatchAsync(string? phoneNumber, string? nationalId, CancellationToken cancellationToken = default)
    {
        var trackId = FinnotechClient.NewTrackId();
        var vendorRef = $"FINNOTECH-SHAHKAR-{trackId}";
        var path = $"mpg/v2/clients/{client.ClientId}/shahkar/verify" +
                   $"?mobile={Uri.EscapeDataString(phoneNumber ?? string.Empty)}" +
                   $"&nationalCode={Uri.EscapeDataString(nationalId ?? string.Empty)}" +
                   $"&trackId={trackId}";

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

        var matched = document.RootElement.TryGetProperty("result", out var result)
                      && result.TryGetProperty("isValid", out var isValid)
                      && isValid.ValueKind == System.Text.Json.JsonValueKind.True;

        return new ShahkarMatchResult(
            Matched: matched,
            IsSharedSim: false,
            VendorRef: vendorRef,
            ExternalResponseJson: raw,
            FailureReason: matched ? null : "The phone number is not registered to your national ID.");
    }
}
