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

namespace CashLineERP.Api.Tests;

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

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

    [Fact]
    public async Task Internal_Onboarding_Case_Workbench_Lists_Public_Supplier_Submissions()
    {
        var publicCreateResponse = await _client.PostAsJsonAsync("/api/v1/public/onboarding/suppliers", new CreatePublicSupplierOnboardingApplicationRequest(
            null,
            "Public Supplier Case",
            "EG",
            null,
            "TAX-PUB-CASE-001",
            "001",
            "public-supplier-case@example.com",
            "+201000000771",
            "Nasr City, Cairo",
            "LOCAL_VENDOR",
            "EGP",
            "BANK_TRANSFER",
            30,
            7,
            1000m,
            "Banque Misr",
            "1234567890098765",
            "BMISEGCX",
            "Public onboarding case test",
            []));
        Assert.Equal(HttpStatusCode.OK, publicCreateResponse.StatusCode);

        var created = await publicCreateResponse.Content.ReadFromJsonAsync<PublicSupplierOnboardingApplicationResponse>();
        Assert.NotNull(created);

        await _client.AuthenticateAsInternalAsync();

        var listResponse = await _client.GetAsync("/api/v1/internal/onboarding/cases?subjectTypeCode=SUPPLIER");
        Assert.Equal(HttpStatusCode.OK, listResponse.StatusCode);

        var cases = await listResponse.Content.ReadFromJsonAsync<IReadOnlyCollection<OnboardingCaseSummaryResponse>>();
        Assert.NotNull(cases);

        var onboardingCase = cases!.Single(item => item.SubjectTypeCode == "SUPPLIER" && item.SubjectProfileId == created!.SupplierProfileId);
        Assert.Equal("PUBLIC_SELF_INITIATED", onboardingCase.InitiationPathCode);
        Assert.Equal("PUBLIC_APPLICANT", onboardingCase.SubmissionSourceCode);
        Assert.Equal("PENDING_APPROVAL", onboardingCase.CaseStatusCode);
        Assert.Equal("ONBOARDING_APPROVAL", onboardingCase.QueueCode);
        Assert.True(onboardingCase.ReadyForApproval);

        var detailResponse = await _client.GetAsync($"/api/v1/internal/onboarding/cases/SUPPLIER/{created.SupplierProfileId}");
        Assert.Equal(HttpStatusCode.OK, detailResponse.StatusCode);

        var detail = await detailResponse.Content.ReadFromJsonAsync<OnboardingCaseDetailResponse>();
        Assert.NotNull(detail);
        Assert.Equal(created.PartyCode, detail!.PartyCode);
        Assert.Equal("PUBLIC_APPLICANT", detail.SubmittedByLoginName);
        Assert.Equal("Public applicant", detail.SubmittedByDisplayName);
        Assert.Equal("SUBMITTED", detail.WorkflowStatusCode);
    }
}
