using CashLineERP.Application.IslamicFinance.ContractTemplates;
using CashLineERP.Application.IslamicFinance.Facilities;
using CashLineERP.Application.IslamicFinance.Murabaha;
using CashLineERP.Application.IslamicFinance.PartnerLenders;
using CashLineERP.Application.IslamicFinance.ProductProfiles;
using CashLineERP.Application.IslamicFinance.Requests;
using CashLineERP.Application.IslamicFinance.Shariah;
using CashLineERP.Contracts.IslamicFinance;
using CashLineERP.Infrastructure.Persistence.Repositories;
using CashLineERP.Infrastructure.Persistence.Repositories.IslamicFinance;
using CashLineERP.SharedKernel.IslamicFinance;

namespace CashLineERP.Api.Tests;

public sealed class IslamicFinanceMurabahaContractServiceQaTests
{
    [Fact]
    public void Murabaha_Contract_Can_Be_Generated_Listed_And_Regenerated_With_Supersede()
    {
        using var dbContext = QaDbContextFactory.CreateContext();

        var partnerService = new IslamicFinancePartnerService(new IslamicFinancePartnerRepository(dbContext));
        var productService = new IslamicFinanceProductService(new IslamicFinanceProductRepository(dbContext));
        var facilityService = new IslamicFinanceFacilityService(new IslamicFinanceFacilityRepository(dbContext));
        var templateService = new IslamicFinanceContractTemplateService(new IslamicFinanceContractTemplateRepository(dbContext));
        var requestRepository = new IslamicFinanceRequestRepository(dbContext);
        var requestService = new IslamicFinanceRequestService(requestRepository);
        var shariahReviewService = new ShariahReviewService(new ShariahReviewRepository(dbContext));
        var murabahaService = new MurabahaCaseService(new MurabahaCaseRepository(dbContext));
        var contractService = new IslamicFinanceMurabahaContractService(
            new IslamicFinanceMurabahaContractRepository(dbContext, new DocumentStorageRepository(dbContext)));

        var partner = CreateActivePartner(partnerService);
        var product = CreateActiveProduct(productService);
        var facility = CreateActiveFacility(facilityService, partner.Id, product.Id);
        var template = CreateActiveTemplate(templateService, product.Id);
        var request = CreateApprovedAssignedRequest(requestService, requestRepository, shariahReviewService, partner.Id, product.Id, facility.Id);

        var created = murabahaService.CreateCase(new CreateIslamicFinanceMurabahaCaseRequest
        {
            CaseNumber = "MUR-CON-SVC-001",
            FinancingRequestId = request.Id,
            CustomerPartyId = 1,
            PartnerLenderId = partner.Id,
            SupplierPartyId = 2,
            ProductProfileId = product.Id,
            ContractTemplateId = template.Id,
            TransactionCurrencyCode = "EGP",
            PurchaseCostAmount = 100000m,
            ProfitAmount = 20000m
        });

        murabahaService.SubmitCase(created.Id, 3);
        murabahaService.ApproveCase(created.Id, 4);

        var first = contractService.GenerateContract(created.Id, 4, new GenerateIslamicFinanceMurabahaContractRequest());
        Assert.Equal(IslamicFinanceDocumentCatalog.MurabahaCaseEntityName, first.EntityName);
        Assert.Equal(IslamicFinanceDocumentCatalog.MurabahaContractDocumentType, first.DocumentType);
        Assert.Equal(1, first.VersionNumber);

        var second = contractService.GenerateContract(created.Id, 4, new GenerateIslamicFinanceMurabahaContractRequest
        {
            ReasonText = "Refresh after template review."
        });

        Assert.Equal(2, second.VersionNumber);

        var list = contractService.GetContracts(created.Id);
        Assert.Equal(2, list.Count);
        Assert.Contains(list, entry => entry.DocumentLinkId == first.DocumentLinkId && entry.LifecycleStatusCode == "SUPERSEDED");
        Assert.Contains(list, entry => entry.DocumentLinkId == second.DocumentLinkId && entry.LifecycleStatusCode == "ACTIVE");

        var detail = contractService.GetContract(created.Id, second.DocumentLinkId);
        Assert.NotNull(detail);
        Assert.Equal(second.DocumentLinkId, detail!.DocumentLinkId);
    }

    private static IslamicFinancePartnerLenderResponse CreateActivePartner(IslamicFinancePartnerService service)
    {
        var created = service.CreatePartnerLender(new CreateIslamicFinancePartnerLenderRequest
        {
            PartnerLenderPartyId = 1,
            DefaultCurrencyCode = "EGP",
            SupportsMurabaha = true,
            SupportsReceivablesFinance = false,
            SupportsTawarruq = false
        });

        service.SubmitPartnerLender(created.Id, 3);
        service.ApprovePartnerLender(created.Id, 4);
        return service.ActivatePartnerLender(created.Id, 4);
    }

    private static IslamicFinanceProductProfileResponse CreateActiveProduct(IslamicFinanceProductService service)
    {
        var created = service.CreateProductProfile(new CreateIslamicFinanceProductProfileRequest
        {
            ProductType = "MURABAHA",
            ProductCode = $"MUR-CON-{Guid.NewGuid():N}"[..12].ToUpperInvariant(),
            ProductName = "Murabaha Contract Product",
            RequiresShariahReview = true,
            AllowsPartnerFunding = true,
            AllowsCashLineFunding = false
        });

        service.SubmitProductProfile(created.Id, 3);
        service.ApproveProductProfile(created.Id, 4);
        return service.ActivateProductProfile(created.Id, 4);
    }

    private static IslamicFinanceFacilityResponse CreateActiveFacility(
        IslamicFinanceFacilityService service,
        long partnerLenderId,
        long productProfileId)
    {
        var created = service.CreateFacility(new CreateIslamicFinanceFacilityRequest
        {
            PartnerLenderId = partnerLenderId,
            CustomerPartyId = 1,
            ProductProfileId = productProfileId,
            FacilityNumber = $"FAC-CON-{Guid.NewGuid():N}"[..12].ToUpperInvariant(),
            CurrencyCode = "EGP",
            ApprovedLimitAmount = 250000m,
            UtilizedAmount = 0m
        });

        service.SubmitFacility(created.Id, 3);
        service.ApproveFacility(created.Id, 4);
        return service.ActivateFacility(created.Id, 4);
    }

    private static IslamicFinanceContractTemplateResponse CreateActiveTemplate(
        IslamicFinanceContractTemplateService service,
        long productProfileId)
    {
        var created = service.CreateContractTemplate(new CreateIslamicFinanceContractTemplateRequest
        {
            ProductProfileId = productProfileId,
            TemplateCode = $"TPL-CON-{Guid.NewGuid():N}"[..12].ToUpperInvariant(),
            TemplateName = "Murabaha Contract Template",
            LanguageCode = "EN"
        });

        service.SubmitContractTemplate(created.Id, 3);
        service.ApproveContractTemplate(created.Id, 4);
        return service.ActivateContractTemplate(created.Id, 4);
    }

    private static IslamicFinanceFinancingRequestResponse CreateApprovedAssignedRequest(
        IslamicFinanceRequestService requestService,
        IslamicFinanceRequestRepository requestRepository,
        ShariahReviewService shariahReviewService,
        long partnerLenderId,
        long productProfileId,
        long facilityId)
    {
        var created = requestService.CreateRequest(new CreateIslamicFinanceFinancingRequestRequest
        {
            RequestNumber = $"REQ-CON-{Guid.NewGuid():N}"[..12].ToUpperInvariant(),
            CustomerPartyId = 1,
            ProductProfileId = productProfileId,
            FacilityId = facilityId,
            FundingSourceMode = "PARTNER",
            SourceDocumentType = "SALES_ORDER",
            SourceDocumentId = 9401,
            TransactionCurrencyCode = "EGP",
            RequestedAmount = 120000m
        });

        requestService.SubmitRequest(created.Id, 3);
        requestService.ApproveRequest(created.Id, 4);

        var review = shariahReviewService.CreateReviewCase(new CreateIslamicFinanceShariahReviewRequest
        {
            ReviewCaseNumber = $"SHR-CON-{Guid.NewGuid():N}"[..12].ToUpperInvariant(),
            ProductProfileId = productProfileId,
            FinancingRequestId = created.Id,
            ReviewReasonCode = "SHARIAH_REVIEW"
        });
        shariahReviewService.SubmitReviewCase(review.Id, 3);
        shariahReviewService.RecommendOutcome(review.Id, new RecommendIslamicFinanceShariahOutcomeRequest
        {
            ReviewOutcomeCode = "APPROVED",
            ReviewNotes = "Approved for Murabaha contract generation."
        }, 3);
        shariahReviewService.ApproveOutcome(review.Id, 4);

        requestService.AttachShariahReview(created.Id, new AttachIslamicFinanceShariahReviewRequest
        {
            ShariahReviewCaseId = review.Id
        }, 3);

        var assigned = requestRepository.AssignPartnerLender(created.Id, partnerLenderId, 3);
        return new IslamicFinanceFinancingRequestResponse
        {
            Id = assigned.FinancingRequestId,
            RequestNumber = assigned.RequestNumber,
            CustomerPartyId = assigned.CustomerPartyId,
            ProductProfileId = assigned.ProductProfileId,
            FacilityId = assigned.FacilityId,
            FundingSourceMode = assigned.FundingSourceMode,
            SourceDocumentType = assigned.SourceDocumentType,
            SourceDocumentId = assigned.SourceDocumentId,
            TransactionCurrencyCode = assigned.TransactionCurrencyCode,
            RequestedAmount = assigned.RequestedAmount,
            StatusCode = assigned.StatusCode,
            AssignedPartnerLenderId = assigned.AssignedPartnerLenderId
        };
    }
}
