using CashLineERP.Domain.Finance;

namespace CashLineERP.Infrastructure.Persistence.Repositories;

internal static class AccountingPeriodLockGuard
{
    public static long RequireOpenPeriod(CashLineErpDbContext dbContext, DateOnly businessDate, string actionDescription)
    {
        var period = dbContext.AccountingPeriods.SingleOrDefault(existingPeriod =>
            existingPeriod.StartDate <= businessDate &&
            existingPeriod.EndDate >= businessDate);

        if (period is null)
        {
            throw new InvalidOperationException(
                $"No accounting period is configured for {actionDescription} dated {businessDate:yyyy-MM-dd}.");
        }

        if (!string.Equals(period.CloseStatusCode, "OPEN", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException(
                $"{actionDescription} dated {businessDate:yyyy-MM-dd} is blocked because accounting period {period.PeriodCode} is {period.CloseStatusCode}.");
        }

        return period.Id;
    }

    public static void EnsureOpenPeriod(CashLineErpDbContext dbContext, DateOnly businessDate, string actionDescription)
    {
        _ = RequireOpenPeriod(dbContext, businessDate, actionDescription);
    }
}
