using Indotalent.ConfigBackEnd.Interfaces;
using Indotalent.Data.Entities;
using Indotalent.Infrastructure.AutoNumberGenerator;
using Indotalent.Shared.Utils;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace Indotalent.Infrastructure.Database;

public static class AppDbContextExtensions
{
    public static async Task<string> GenerateAutoNumberAsync(
    this AppDbContext context,
    string entityName,
    string prefixTemplate,
    string? suffixTemplate = null,
    int paddingLength = 4,
    bool useYear = true,
    bool useMonth = false,
    CancellationToken ct = default)
    {
        var currentUserService = context.GetService<ICurrentUserService>();
        var tenantId = currentUserService?.TenantId;

        if (string.IsNullOrWhiteSpace(tenantId))
        {
            throw new InvalidOperationException("TenantId cannot be null or empty for multi-tenant auto-number sequence generation. Ensure the user session context is valid.");
        }

        var generator = context.GetService<AutoNumberGeneratorService>();

        return await generator.GenerateNextNumberAsync(
            tenantId,
            entityName,
            prefixTemplate,
            suffixTemplate,
            paddingLength,
            useYear,
            useMonth,
            ct);
    }

    public static void CalculateInvenTrans(this AppDbContext context, InventoryTransaction transaction)
    {
        InventoryTransactionHelper.CalculateInvenTrans(context, transaction);
    }
    public static double GetStock(this AppDbContext context, string? warehouseId, string? productId, string? currentId = null)
    {
        return InventoryTransactionHelper.GetStock(context, warehouseId, productId, currentId);
    }
    public static void RecalculatePurchaseOrder(this AppDbContext context, string purchaseOrderId)
    {
        PurchaseOrderHelper.Recalculate(context, purchaseOrderId);
    }
    public static void RecalculatePurchaseRequisition(this AppDbContext context, string requisitionId)
    {
        PurchaseRequisitionHelper.Recalculate(context, requisitionId);
    }
    public static void RecalculateSalesOrder(this AppDbContext context, string salesOrderId)
    {
        SalesOrderHelper.Recalculate(context, salesOrderId);
    }
    public static void RecalculateSalesQuotation(this AppDbContext context, string quotationId)
    {
        SalesQuotationHelper.Recalculate(context, quotationId);
    }
}
