using CashLineERP.Application.IslamicFinance.PartnerLenders;
using CashLineERP.Contracts.IslamicFinance;
using CashLineERP.Infrastructure.Persistence.Repositories.IslamicFinance;

namespace CashLineERP.Api.Tests;

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

        var service = new IslamicFinancePartnerService(new IslamicFinancePartnerRepository(dbContext));

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

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

        var submitted = service.SubmitPartnerLender(created.Id, 3);
        Assert.Equal("SUBMITTED", submitted.StatusCode);

        var approved = service.ApprovePartnerLender(created.Id, 4);
        Assert.Equal("APPROVED", approved.StatusCode);

        var activated = service.ActivatePartnerLender(created.Id, 4);
        Assert.Equal("ACTIVE", activated.StatusCode);
        Assert.True(activated.IsActive);

        var detail = service.GetPartnerLender(created.Id);
        Assert.NotNull(detail);
        Assert.Equal(created.Id, detail!.Id);

        var activeList = service.GetPartnerLenders(activeOnly: true);
        Assert.Single(activeList);
    }

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

        var service = new IslamicFinancePartnerService(new IslamicFinancePartnerRepository(dbContext));

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

        service.SubmitPartnerLender(created.Id, 3);

        var exception = Assert.Throws<InvalidOperationException>(() =>
            service.ApprovePartnerLender(created.Id, 3));

        Assert.Contains("maker-checker", exception.Message, StringComparison.OrdinalIgnoreCase);
    }
}
