using System.Net;
using System.Net.Http.Json;
using CashLineERP.Contracts.External;
using CashLineERP.Contracts.Parties;

namespace CashLineERP.Api.Tests;

public sealed class OnboardingPolicyQaTests : IClassFixture<ApiTestFactory>
{
    private readonly HttpClient _client;
    private readonly ApiTestFactory _factory;

    public OnboardingPolicyQaTests(ApiTestFactory factory)
    {
        _factory = factory;
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task Public_Supplier_Onboarding_Evaluation_Exposes_URD_Gaps_As_Blocking_Issues()
    {
        var response = await _client.PostAsJsonAsync("/api/v1/public/onboarding/suppliers/evaluate", new CreatePublicSupplierOnboardingApplicationRequest(
            null,
            "Policy Supplier",
            "EG",
            null,
            "TAX-SUP-POLICY-001",
            "001",
            "policy.supplier@example.com",
            "+201000000451",
            "Cairo",
            "LOCAL_VENDOR",
            "EGP",
            "BANK_TRANSFER",
            30,
            7,
            1000m,
            "Banque Misr",
            "001122334455",
            "BMISEGCX",
            "Policy evaluation",
            [
                new RecordBusinessPartyComplianceDocumentRequest(
                    "COMMERCIAL_REGISTER",
                    "commercial-register.pdf",
                    "managed://policy/supplier/commercial-register.pdf",
                    "application/pdf",
                    1024)
            ]));

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var payload = await response.Content.ReadFromJsonAsync<OnboardingCompletenessEvaluationResponse>();
        Assert.NotNull(payload);
        Assert.False(payload!.ReadyForSubmission);
        Assert.Contains(payload.KycFieldEvaluations, entry => entry.FieldCode == "TRADE_NAME" && entry.StatusCode == "MISSING_FROM_CURRENT_IMPLEMENTATION");
        Assert.Contains(payload.DocumentChecklistEvaluations, entry => entry.ChecklistItemCode == "BANK_CONFIRMATION" && !entry.IsSatisfied);
    }

    [Fact]
    public async Task Internal_Supplier_Policy_Exposes_Missing_Trade_Name_Field()
    {
        using var authenticatedClient = _factory.CreateClient();
        await authenticatedClient.AuthenticateAsInternalAsync();

        var response = await authenticatedClient.GetAsync("/api/v1/onboarding/policies/suppliers?onboardingPathCode=INTERNAL_MANUAL");

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var payload = await response.Content.ReadFromJsonAsync<OnboardingPolicyResponse>();
        Assert.NotNull(payload);
        Assert.Equal("INTERNAL_MANUAL", payload!.OnboardingPathCode);
        Assert.Contains(payload.KycFields, entry => entry.FieldCode == "TRADE_NAME" && entry.CoverageCode == "MISSING");
    }
}
