using System.Diagnostics;
using CashLineERP.Application.Internal;
using CashLineERP.Application.Finance;
using CashLineERP.Application.IslamicFinance.Disbursements;
using CashLineERP.Application.IslamicFinance.Murabaha;
using CashLineERP.Application.IslamicFinance.Requests;
using CashLineERP.Application.Reporting;
using CashLineERP.Contracts.Finance;
using CashLineERP.Infrastructure.Persistence.Repositories;
using CashLineERP.Infrastructure.Persistence.Repositories.IslamicFinance;

namespace CashLineERP.Api.Tests;

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

        var reportingService = new CoreReportingService(new CoreReportingRepository(dbContext));
        var invoiceService = new AccountsReceivableInvoiceService(new AccountsReceivableInvoiceRepository(dbContext));
        var receiptService = new AccountsReceivableReceiptService(new AccountsReceivableReceiptRepository(dbContext));

        var createdInvoice = invoiceService.CreateInvoice(new CreateAccountsReceivableInvoiceRequest(
            CustomerId: 2,
            SalesOrderId: 1,
            DispatchOrderId: 1,
            InvoiceType: "TAX",
            InvoiceDate: new DateOnly(2026, 4, 28),
            TaxDate: new DateOnly(2026, 4, 28),
            DueDate: new DateOnly(2026, 4, 30),
            CurrencyCode: "USD",
            Lines:
            [
                new CreateAccountsReceivableInvoiceLineRequest(1, 1001, 2m, "EA", 18m, "VAT14")
            ]));
        var postedInvoice = AccountsReceivableWorkflowTestHelper.SubmitApproveAndPostInvoice(invoiceService, createdInvoice.AccountsReceivableInvoiceId);

        var createdReceipt = receiptService.CreateReceipt(new CreateAccountsReceivableReceiptRequest(
            CustomerId: 2,
            ReceiptDate: new DateOnly(2026, 4, 29),
            ReceiptMethod: "BANK_TRANSFER",
            CurrencyCode: "USD",
            AmountAmount: postedInvoice.TotalAmount,
            ReferenceNumber: "LOAD-ENDURANCE-FIN-01",
            Notes: "Expanded finance reporting load baseline.",
            Allocations:
            [
                new CreateAccountsReceivableReceiptAllocationRequest(postedInvoice.AccountsReceivableInvoiceId, postedInvoice.TotalAmount, new DateOnly(2026, 4, 29))
            ]));
        AccountsReceivableWorkflowTestHelper.SubmitApproveAndPostReceipt(receiptService, createdReceipt.AccountsReceivableReceiptId);

        var stopwatch = Stopwatch.StartNew();

        for (var index = 0; index < 80; index++)
        {
            reportingService.GetFinancialStatementReport("BALANCE_SHEET", null, null, new DateOnly(2026, 4, 29));
            reportingService.GetFinancialStatementReport("INCOME_STATEMENT", new DateOnly(2026, 4, 1), new DateOnly(2026, 4, 29), null);
            reportingService.GetFinancialStatementReport("CASH_FLOW", new DateOnly(2026, 4, 1), new DateOnly(2026, 4, 29), null);
            reportingService.GetFinancialStatementReport("TRIAL_BALANCE", new DateOnly(2026, 4, 1), new DateOnly(2026, 4, 29), new DateOnly(2026, 4, 29));
            reportingService.GetFinancialStatementReport("ACCOUNTING_ENTRIES", new DateOnly(2026, 4, 1), new DateOnly(2026, 4, 29), null);
            reportingService.GetFinanceStakeholderSummaryReport(new DateOnly(2026, 4, 1), new DateOnly(2026, 4, 29));
        }

        stopwatch.Stop();

        Assert.True(
            stopwatch.Elapsed < TimeSpan.FromSeconds(12),
            $"Expanded finance-reporting load baseline exceeded threshold. Elapsed: {stopwatch.Elapsed}.");
    }

    [Fact]
    public void Islamic_Finance_History_Audit_And_Pipeline_Reads_Stay_Within_Endurance_Baseline()
    {
        using var dbContext = QaDbContextFactory.CreateContext();

        var seed = IslamicFinanceIntegrationTestSeeder.SeedOperationalLifecycle(dbContext);
        var requestService = new IslamicFinanceRequestService(new IslamicFinanceRequestRepository(dbContext));
        var murabahaCaseService = new MurabahaCaseService(new MurabahaCaseRepository(dbContext));
        var disbursementService = new IslamicFinanceMurabahaDisbursementService(new IslamicFinanceMurabahaDisbursementRepository(dbContext));
        var reportingService = new CoreReportingService(new CoreReportingRepository(dbContext));
        var internalWorkbenchService = new InternalWorkbenchService(new InternalWorkbenchRepository(dbContext));

        var stopwatch = Stopwatch.StartNew();

        for (var index = 0; index < 150; index++)
        {
            requestService.GetRequestHistory(seed.FinancingRequestId);
            requestService.GetRequestAudit(seed.FinancingRequestId);
            requestService.GetDecisionAudit(seed.FinancingDecisionId);
            murabahaCaseService.GetCaseHistory(seed.MurabahaCaseId);
            murabahaCaseService.GetCaseAudit(seed.MurabahaCaseId);
            disbursementService.GetDisbursementHistory(seed.DisbursementId);
            disbursementService.GetDisbursementAudit(seed.DisbursementId);
            reportingService.GetIslamicFinancePipelineReport(new DateOnly(2026, 4, 1), new DateOnly(2026, 4, 30), seed.PartnerLenderId);
            internalWorkbenchService.GetWorkflowMonitoring("Testing", "1.0.0.0", itemLimit: 5);
        }

        stopwatch.Stop();

        Assert.True(
            stopwatch.Elapsed < TimeSpan.FromSeconds(12),
            $"Islamic Finance endurance baseline exceeded threshold. Elapsed: {stopwatch.Elapsed}.");
    }
}
