using Meezi.Core.Constants;
using Meezi.Core.Enums;

namespace Meezi.API.Services;

public static class ReportPlanGate
{
    public static bool IsDateInRange(PlanTier tier, DateOnly date, DateOnly todayIran)
    {
        var maxDays = PlanLimits.MaxReportHistoryDays(tier);
        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(
        PlanTier tier,
        DateOnly from,
        DateOnly to,
        DateOnly todayIran)
    {
        if (from > to) return null;
        if (!IsDateInRange(tier, to, todayIran) || !IsDateInRange(tier, from, todayIran))
            return null;

        var maxDays = PlanLimits.MaxReportHistoryDays(tier);
        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(PlanTier tier)
    {
        var days = PlanLimits.MaxReportHistoryDays(tier);
        return tier switch
        {
            PlanTier.Free =>
                "Daily reports on the Free plan are limited to today and the previous 7 days. Upgrade to Pro for 90 days of history.",
            PlanTier.Pro =>
                "Daily reports on the Pro plan are limited to the last 90 days. Upgrade to Business for unlimited history.",
            _ => "Report date is outside your plan range."
        };
    }
}
