using CashLineERP.Domain.Common;
using CashLineERP.SharedKernel.IslamicFinance;
using System.ComponentModel.DataAnnotations.Schema;

namespace CashLineERP.Domain.IslamicFinance.Murabaha;

public sealed class IslamicFinanceMurabahaCase : Entity
{
    public long Id { get; private set; }
    public string CaseNumber { get; private set; } = string.Empty;
    public long FinancingRequestId { get; private set; }
    public long CustomerPartyId { get; private set; }
    public long PartnerLenderId { get; private set; }
    public long? SupplierPartyId { get; private set; }
    public long ProductProfileId { get; private set; }
    public long? ContractTemplateId { get; private set; }
    public string TransactionCurrencyCode { get; private set; } = string.Empty;
    public decimal PurchaseCostAmount { get; private set; }
    public decimal ProfitAmount { get; private set; }
    public decimal SalePriceAmount { get; private set; }
    public string StatusCode { get; private set; } = IslamicFinanceWorkflowCatalog.Draft;
    public long? WorkflowInstanceId { get; private set; }
    public DateTime? SubmittedAtUtc { get; private set; }
    public long? SubmittedByUserId { get; private set; }
    public DateTime? ApprovedAtUtc { get; private set; }
    public long? ApprovedByUserId { get; private set; }
    public DateTime? ActivatedAtUtc { get; private set; }
    public long? ActivatedByUserId { get; private set; }
    [NotMapped]
    public IslamicFinanceLifecycleState LifecycleState => IslamicFinanceWorkflowCatalog.ParseStatusCode(StatusCode);

    public IslamicFinanceMurabahaCase(
        string caseNumber,
        long financingRequestId,
        long customerPartyId,
        long partnerLenderId,
        long? supplierPartyId,
        long productProfileId,
        long? contractTemplateId,
        string transactionCurrencyCode,
        decimal purchaseCostAmount,
        decimal profitAmount)
    {
        if (string.IsNullOrWhiteSpace(caseNumber))
        {
            throw new InvalidOperationException("Islamic Finance Murabaha case number is required.");
        }

        if (financingRequestId <= 0 || customerPartyId <= 0 || partnerLenderId <= 0 || productProfileId <= 0)
        {
            throw new InvalidOperationException("Islamic Finance Murabaha case requires valid request, customer, partner-lender, and product-profile identifiers.");
        }

        if (supplierPartyId.HasValue && supplierPartyId.Value <= 0)
        {
            throw new InvalidOperationException("Islamic Finance Murabaha supplier party identifier must be positive when provided.");
        }

        if (contractTemplateId.HasValue && contractTemplateId.Value <= 0)
        {
            throw new InvalidOperationException("Islamic Finance Murabaha contract template identifier must be positive when provided.");
        }

        if (string.IsNullOrWhiteSpace(transactionCurrencyCode))
        {
            throw new InvalidOperationException("Islamic Finance Murabaha transaction currency code is required.");
        }

        if (purchaseCostAmount <= 0m || profitAmount < 0m)
        {
            throw new InvalidOperationException("Islamic Finance Murabaha case requires positive purchase cost and non-negative profit.");
        }

        CaseNumber = caseNumber.Trim().ToUpperInvariant();
        FinancingRequestId = financingRequestId;
        CustomerPartyId = customerPartyId;
        PartnerLenderId = partnerLenderId;
        SupplierPartyId = supplierPartyId;
        ProductProfileId = productProfileId;
        ContractTemplateId = contractTemplateId;
        TransactionCurrencyCode = transactionCurrencyCode.Trim().ToUpperInvariant();
        PurchaseCostAmount = purchaseCostAmount;
        ProfitAmount = profitAmount;
        SalePriceAmount = purchaseCostAmount + profitAmount;
    }

    private IslamicFinanceMurabahaCase()
    {
    }

    public void Submit(long actorUserId)
    {
        if (!string.Equals(StatusCode, IslamicFinanceWorkflowCatalog.Draft, StringComparison.OrdinalIgnoreCase)
            && !string.Equals(StatusCode, IslamicFinanceWorkflowCatalog.Returned, StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("Only draft or returned Islamic Finance Murabaha cases can be submitted.");
        }

        StatusCode = IslamicFinanceWorkflowCatalog.Submitted;
        SubmittedAtUtc = DateTime.UtcNow;
        SubmittedByUserId = actorUserId;
        ApprovedAtUtc = null;
        ApprovedByUserId = null;
        Touch(actorUserId);
    }

    public void Approve(long actorUserId)
    {
        if (string.Equals(StatusCode, IslamicFinanceWorkflowCatalog.Approved, StringComparison.OrdinalIgnoreCase))
        {
            return;
        }

        if (!string.Equals(StatusCode, IslamicFinanceWorkflowCatalog.Submitted, StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("Only submitted Islamic Finance Murabaha cases can be approved.");
        }

        if (SubmittedByUserId == actorUserId)
        {
            throw new InvalidOperationException("Islamic Finance Murabaha maker-checker control prohibits self-approval.");
        }

        StatusCode = IslamicFinanceWorkflowCatalog.Approved;
        ApprovedAtUtc = DateTime.UtcNow;
        ApprovedByUserId = actorUserId;
        Touch(actorUserId);
    }

    public void Activate(long actorUserId)
    {
        if (string.Equals(StatusCode, IslamicFinanceWorkflowCatalog.Active, StringComparison.OrdinalIgnoreCase))
        {
            return;
        }

        if (!string.Equals(StatusCode, IslamicFinanceWorkflowCatalog.Approved, StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("Only approved Islamic Finance Murabaha cases can be activated.");
        }

        StatusCode = IslamicFinanceWorkflowCatalog.Active;
        ActivatedAtUtc = DateTime.UtcNow;
        ActivatedByUserId = actorUserId;
        Touch(actorUserId);
    }
}
