using CashLineERP.Application.IslamicFinance.ContractTemplates;
using CashLineERP.Application.IslamicFinance.ProductProfiles;
using CashLineERP.Contracts.IslamicFinance;
using CashLineERP.Infrastructure.Persistence.Repositories.IslamicFinance;

namespace CashLineERP.Api.Tests;

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

        var productService = new IslamicFinanceProductService(new IslamicFinanceProductRepository(dbContext));
        var templateService = new IslamicFinanceContractTemplateService(new IslamicFinanceContractTemplateRepository(dbContext));

        var product = CreateActiveProduct(productService);

        var created = templateService.CreateContractTemplate(new CreateIslamicFinanceContractTemplateRequest
        {
            ProductProfileId = product.Id,
            TemplateCode = "MUR-TPL-SVC-001",
            TemplateName = "Murabaha Arabic Contract",
            LanguageCode = "AR"
        });

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

        templateService.SubmitContractTemplate(created.Id, 3);
        templateService.ApproveContractTemplate(created.Id, 4);
        var activated = templateService.ActivateContractTemplate(created.Id, 4);

        Assert.True(activated.IsActive);
        Assert.Equal("ACTIVE", activated.StatusCode);

        var detail = templateService.GetContractTemplate(created.Id);
        Assert.NotNull(detail);
        Assert.Equal(created.Id, detail!.Id);

        var filtered = templateService.GetContractTemplates(activeOnly: true, productProfileId: product.Id, languageCode: "AR");
        Assert.Single(filtered);
    }

    private static IslamicFinanceProductProfileResponse CreateActiveProduct(IslamicFinanceProductService service)
    {
        var created = service.CreateProductProfile(new CreateIslamicFinanceProductProfileRequest
        {
            ProductType = "MURABAHA",
            ProductCode = $"MUR-TPL-{Guid.NewGuid():N}"[..14].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);
    }
}
