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

namespace CashLineERP.Api.Tests;

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

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

    [Fact]
    public async Task Internal_And_External_Party_Compliance_Document_Endpoints_Work()
    {
        await _client.AuthenticateAsInternalAsync();

        var internalCreateResponse = await _client.PostAsJsonAsync("/api/v1/parties/1/compliance-documents", new RecordBusinessPartyComplianceDocumentRequest(
            DocumentType: "commercial_register",
            FileName: "commercial-register.pdf",
            StorageReference: "party/1/commercial-register.pdf",
            ContentType: "application/pdf",
            FileSizeBytes: 4096));
        Assert.Equal(HttpStatusCode.OK, internalCreateResponse.StatusCode);

        var createdInternalDocument = await internalCreateResponse.Content.ReadFromJsonAsync<BusinessPartyComplianceDocumentResponse>();
        Assert.NotNull(createdInternalDocument);
        Assert.Equal("COMMERCIAL_REGISTER", createdInternalDocument!.DocumentType);

        var internalListResponse = await _client.GetAsync("/api/v1/parties/1/compliance-documents");
        Assert.Equal(HttpStatusCode.OK, internalListResponse.StatusCode);
        var internalDocuments = await internalListResponse.Content.ReadFromJsonAsync<List<BusinessPartyComplianceDocumentResponse>>();
        Assert.NotNull(internalDocuments);
        Assert.Contains(internalDocuments!, entry => entry.DocumentLinkId == createdInternalDocument.DocumentLinkId);

        await _client.AuthenticateAsSupplierAsync();

        var externalCreateResponse = await _client.PostAsJsonAsync("/api/v1/external/parties/1/compliance-documents", new RecordBusinessPartyComplianceDocumentRequest(
            DocumentType: "vat_certificate",
            FileName: "vat-certificate.pdf",
            StorageReference: "party/1/vat-certificate.pdf",
            ContentType: "application/pdf",
            FileSizeBytes: 1024));
        Assert.Equal(HttpStatusCode.OK, externalCreateResponse.StatusCode);

        var externalListResponse = await _client.GetAsync("/api/v1/external/parties/1/compliance-documents");
        Assert.Equal(HttpStatusCode.OK, externalListResponse.StatusCode);
        var externalDocuments = await externalListResponse.Content.ReadFromJsonAsync<List<BusinessPartyComplianceDocumentResponse>>();
        Assert.NotNull(externalDocuments);
        Assert.Contains(externalDocuments!, entry => entry.DocumentType == "VAT_CERTIFICATE");

        var forbiddenResponse = await _client.GetAsync("/api/v1/external/parties/2/compliance-documents");
        Assert.Equal(HttpStatusCode.Forbidden, forbiddenResponse.StatusCode);
    }
}
