using System.Linq;
using CashLineERP.Application.IslamicFinance.ContractTemplates;
using CashLineERP.Application.IslamicFinance.Disbursements;
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.Settlements;
using CashLineERP.Application.IslamicFinance.Shariah;
using CashLineERP.Contracts.IslamicFinance;
using CashLineERP.Domain.IslamicFinance.Murabaha;
using CashLineERP.Infrastructure.Persistence;
using CashLineERP.Infrastructure.Persistence.Repositories;
using CashLineERP.Infrastructure.Persistence.Repositories.IslamicFinance;

namespace CashLineERP.Api.Tests;

public sealed class IslamicFinanceMurabahaDisbursementServiceQaTests
{
    [Fact]
    public void Murabaha_Disbursement_Service_Supports_Create_List_Detail_And_Execute()
    {
        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 murabahaCaseRepository = new MurabahaCaseRepository(dbContext);
        var murabahaCaseService = new MurabahaCaseService(murabahaCaseRepository);
        var murabahaContractService = new IslamicFinanceMurabahaContractService(
            new IslamicFinanceMurabahaContractRepository(dbContext, new DocumentStorageRepository(dbContext)));
        var disbursementService = new IslamicFinanceMurabahaDisbursementService(
            new IslamicFinanceMurabahaDisbursementRepository(dbContext));

        var murabahaCaseId = SeedMurabahaCaseReadyForDisbursement(
            dbContext,
            partnerService,
            productService,
            facilityService,
            templateService,
            requestService,
            requestRepository,
            shariahReviewService,
            murabahaCaseService,
            murabahaContractService,
            "MUR-DSVC");

        var created = disbursementService.CreateDisbursement(new CreateIslamicFinanceMurabahaDisbursementRequest
        {
            MurabahaCaseId = murabahaCaseId,
            DisbursementNumber = "IFD-SVC-0001",
            TargetType = "SUPPLIER_PAYMENT",
            InstructedAmount = 60000m,
            PlannedExecutionDate = new DateOnly(2026, 4, 7)
        });

        Assert.Equal("DRAFT", created.StatusCode);
        Assert.Equal("SUPPLIER_PAYMENT", created.TargetType);

        disbursementService.SubmitDisbursement(created.Id, 10);
        disbursementService.ApproveDisbursement(created.Id, 11);
        var executed = disbursementService.ExecuteDisbursement(created.Id, new ExecuteIslamicFinanceMurabahaDisbursementRequest
        {
            ExecutionReferenceNumber = "PAY-SVC-0001"
        }, 12);

        Assert.Equal("ACTIVE", executed.StatusCode);
        Assert.Equal(60000m, executed.ExecutedAmount);
        Assert.Equal(0m, executed.OutstandingAmount);
        Assert.NotNull(executed.ExecutedAtUtc);

        var list = disbursementService.GetDisbursements(murabahaCaseId: murabahaCaseId);
        Assert.Single(list);

        var detail = disbursementService.GetDisbursement(created.Id);
        Assert.NotNull(detail);
        Assert.Equal(created.Id, detail!.Id);

        var murabahaCase = murabahaCaseService.GetCase(murabahaCaseId);
        Assert.NotNull(murabahaCase);
        Assert.Equal("ACTIVE", murabahaCase!.StatusCode);
    }

    [Fact]
    public void Murabaha_Disbursement_Service_Rejects_Create_When_Purchase_Cost_Envelope_Is_Exceeded()
    {
        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 murabahaCaseService = new MurabahaCaseService(new MurabahaCaseRepository(dbContext));
        var murabahaContractService = new IslamicFinanceMurabahaContractService(
            new IslamicFinanceMurabahaContractRepository(dbContext, new DocumentStorageRepository(dbContext)));
        var disbursementService = new IslamicFinanceMurabahaDisbursementService(
            new IslamicFinanceMurabahaDisbursementRepository(dbContext));

        var murabahaCaseId = SeedMurabahaCaseReadyForDisbursement(
            dbContext,
            partnerService,
            productService,
            facilityService,
            templateService,
            requestService,
            requestRepository,
            shariahReviewService,
            murabahaCaseService,
            murabahaContractService,
            "MUR-DLIM");

        disbursementService.CreateDisbursement(new CreateIslamicFinanceMurabahaDisbursementRequest
        {
            MurabahaCaseId = murabahaCaseId,
            DisbursementNumber = "IFD-LIM-0001",
            TargetType = "SUPPLIER_PAYMENT",
            InstructedAmount = 70000m,
            PlannedExecutionDate = new DateOnly(2026, 4, 7)
        });

        Assert.Throws<InvalidOperationException>(() => disbursementService.CreateDisbursement(new CreateIslamicFinanceMurabahaDisbursementRequest
        {
            MurabahaCaseId = murabahaCaseId,
            DisbursementNumber = "IFD-LIM-0002",
            TargetType = "SUPPLIER_PAYMENT",
            InstructedAmount = 40000m,
            PlannedExecutionDate = new DateOnly(2026, 4, 8)
        }));
    }

    [Fact]
    public void Murabaha_Disbursement_Service_Returns_History_And_Audit_With_Settlement_Linkage()
    {
        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 murabahaCaseService = new MurabahaCaseService(new MurabahaCaseRepository(dbContext));
        var murabahaContractService = new IslamicFinanceMurabahaContractService(
            new IslamicFinanceMurabahaContractRepository(dbContext, new DocumentStorageRepository(dbContext)));
        var disbursementService = new IslamicFinanceMurabahaDisbursementService(
            new IslamicFinanceMurabahaDisbursementRepository(dbContext));
        var settlementService = new IslamicFinanceSettlementService(new IslamicFinanceSettlementRepository(dbContext));

        var murabahaCaseId = SeedMurabahaCaseReadyForDisbursement(
            dbContext,
            partnerService,
            productService,
            facilityService,
            templateService,
            requestService,
            requestRepository,
            shariahReviewService,
            murabahaCaseService,
            murabahaContractService,
            "MUR-DHST");

        var disbursement = disbursementService.CreateDisbursement(new CreateIslamicFinanceMurabahaDisbursementRequest
        {
            MurabahaCaseId = murabahaCaseId,
            DisbursementNumber = "IFD-HIST-0001",
            TargetType = "SUPPLIER_PAYMENT",
            InstructedAmount = 60000m,
            PlannedExecutionDate = new DateOnly(2026, 4, 7)
        });
        disbursementService.SubmitDisbursement(disbursement.Id, 10);
        disbursementService.ApproveDisbursement(disbursement.Id, 11);
        var executed = disbursementService.ExecuteDisbursement(disbursement.Id, new ExecuteIslamicFinanceMurabahaDisbursementRequest
        {
            ExecutionReferenceNumber = "PAY-HIST-0001"
        }, 12);

        settlementService.CreateSettlement(new CreateIslamicFinanceSettlementRequest
        {
            SettlementNumber = "IFS-DHST-0001",
            MurabahaCaseId = murabahaCaseId,
            SettlementDate = new DateOnly(2026, 4, 10),
            SettlementCurrencyCode = "EGP",
            Lines =
            [
                new CreateIslamicFinanceSettlementLineRequest
                {
                    MurabahaDisbursementId = executed.Id,
                    SettledAmount = executed.ExecutedAmount
                }
            ]
        });

        var history = disbursementService.GetDisbursementHistory(executed.Id);
        Assert.Contains(history, entry => entry.EventCode == "DISBURSEMENT_CREATED");
        Assert.Contains(history, entry => entry.EventCode == "DISBURSEMENT_EXECUTED");
        Assert.Contains(history, entry => entry.EventCode == "SETTLEMENT_LINKED");
        Assert.True(history.SequenceEqual(history.OrderBy(entry => entry.OccurredAtUtc)));

        var audit = disbursementService.GetDisbursementAudit(executed.Id);
        Assert.NotNull(audit);
        Assert.Equal(executed.Id, audit!.Disbursement.Id);
        Assert.Contains(audit.Events, entry => entry.EventCode == "SETTLEMENT_LINKED");
    }

    private static long SeedMurabahaCaseReadyForDisbursement(
        CashLineErpDbContext dbContext,
        IslamicFinancePartnerService partnerService,
        IslamicFinanceProductService productService,
        IslamicFinanceFacilityService facilityService,
        IslamicFinanceContractTemplateService templateService,
        IslamicFinanceRequestService requestService,
        IslamicFinanceRequestRepository requestRepository,
        ShariahReviewService shariahReviewService,
        MurabahaCaseService murabahaCaseService,
        IslamicFinanceMurabahaContractService murabahaContractService,
        string prefix)
    {
        var partner = CreateActivePartner(partnerService);
        var product = CreateActiveProduct(productService, prefix);
        var facility = CreateActiveFacility(facilityService, partner.Id, product.Id, prefix);
        var template = CreateActiveTemplate(templateService, product.Id, prefix);
        var request = CreateApprovedAssignedRequest(requestService, requestRepository, shariahReviewService, partner.Id, product.Id, facility.Id, prefix);

        var murabahaCase = murabahaCaseService.CreateCase(new CreateIslamicFinanceMurabahaCaseRequest
        {
            CaseNumber = $"{prefix}-{Guid.NewGuid():N}"[..12].ToUpperInvariant(),
            FinancingRequestId = request.Id,
            CustomerPartyId = 1,
            PartnerLenderId = partner.Id,
            SupplierPartyId = 2,
            ProductProfileId = product.Id,
            ContractTemplateId = template.Id,
            TransactionCurrencyCode = "EGP",
            PurchaseCostAmount = 100000m,
            ProfitAmount = 20000m
        });

        murabahaCaseService.SubmitCase(murabahaCase.Id, 3);
        murabahaCaseService.ApproveCase(murabahaCase.Id, 4);
        murabahaCaseService.ActivateCase(murabahaCase.Id, 4);
        murabahaContractService.GenerateContract(murabahaCase.Id, 4, new GenerateIslamicFinanceMurabahaContractRequest());

        dbContext.IslamicFinanceProfitSchedules.AddRange(
            new IslamicFinanceProfitSchedule(murabahaCase.Id, 1, new DateOnly(2026, 5, 1), 50000m, 10000m, 60000m),
            new IslamicFinanceProfitSchedule(murabahaCase.Id, 2, new DateOnly(2026, 6, 1), 50000m, 10000m, 0m));
        dbContext.SaveChanges();

        return murabahaCase.Id;
    }

    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, string prefix)
    {
        var created = service.CreateProductProfile(new CreateIslamicFinanceProductProfileRequest
        {
            ProductType = "MURABAHA",
            ProductCode = $"{prefix}-{Guid.NewGuid():N}"[..12].ToUpperInvariant(),
            ProductName = $"{prefix} 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,
        string prefix)
    {
        var created = service.CreateFacility(new CreateIslamicFinanceFacilityRequest
        {
            PartnerLenderId = partnerLenderId,
            CustomerPartyId = 1,
            ProductProfileId = productProfileId,
            FacilityNumber = $"{prefix}-{Guid.NewGuid():N}"[..12].ToUpperInvariant(),
            CurrencyCode = "EGP",
            ApprovedLimitAmount = 300000m,
            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,
        string prefix)
    {
        var created = service.CreateContractTemplate(new CreateIslamicFinanceContractTemplateRequest
        {
            ProductProfileId = productProfileId,
            TemplateCode = $"{prefix}-{Guid.NewGuid():N}"[..12].ToUpperInvariant(),
            TemplateName = $"{prefix} 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,
        string prefix)
    {
        var created = requestService.CreateRequest(new CreateIslamicFinanceFinancingRequestRequest
        {
            RequestNumber = $"{prefix}-{Guid.NewGuid():N}"[..12].ToUpperInvariant(),
            CustomerPartyId = 1,
            ProductProfileId = productProfileId,
            FacilityId = facilityId,
            FundingSourceMode = "PARTNER",
            SourceDocumentType = "SALES_ORDER",
            SourceDocumentId = 9901,
            TransactionCurrencyCode = "EGP",
            RequestedAmount = 120000m
        });

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

        var review = shariahReviewService.CreateReviewCase(new CreateIslamicFinanceShariahReviewRequest
        {
            ReviewCaseNumber = $"{prefix}-{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 disbursement QA."
        }, 3);
        shariahReviewService.ApproveOutcome(review.Id, 4);

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