namespace Meezi.API.Services;

/// <summary>
/// Report-history window checks. Takes the (admin-editable) max-history days
/// directly so the limit comes from the plan catalog, not a hardcoded tier table.
/// </summary>
public static class ReportPlanGate
{
    public static bool IsDateInRange(int maxDays, DateOnly date, DateOnly todayIran)
    {
        if (maxDays == int.MaxValue)
            return date <= todayIran;

        var earliest = todayIran.AddDays(-(maxDays - 1));
        return date >= earliest && date <= todayIran;
    }

    public static (DateOnly From, DateOnly To)? ClampRange(
        int maxDays,
        DateOnly from,
        DateOnly to,
        DateOnly todayIran)
    {
        if (from > to) return null;
        if (!IsDateInRange(maxDays, to, todayIran) || !IsDateInRange(maxDays, from, todayIran))
            return null;

        if (maxDays == int.MaxValue)
            return (from, to);

        var earliest = todayIran.AddDays(-(maxDays - 1));
        var clampedFrom = from < earliest ? earliest : from;
        var clampedTo = to > todayIran ? todayIran : to;
        if (clampedFrom > clampedTo) return null;
        return (clampedFrom, clampedTo);
    }

    public static string LimitMessage(int maxDays) =>
        maxDays == int.MaxValue
            ? "Report date is outside the allowed range."
            : $"Daily reports on your plan are limited to the last {maxDays} days. Upgrade for more history.";
}
