namespace BigRegister.Domain.Registrations;

/// <summary>
/// SERVER-OWNED business rule (ported from the frontend reference impl
/// registration.policy.ts:isHerregistratieEligible). A registration may apply for
/// herregistratie only while active and within the window before its deadline.
/// The endpoint ships the result as a decision flag + reason; the frontend renders it.
/// </summary>
public static class HerregistratieRule
{
    public const int WindowMonths = 12;

    public static DateOnly? Deadline(Registration reg) =>
        reg.Status.Tag == StatusTag.Geregistreerd ? reg.Status.HerregistratieDatum : null;

    public static (bool Eligible, string? Reason) Evaluate(
        Registration reg, DateOnly today, int windowMonths = WindowMonths)
    {
        var deadline = Deadline(reg);
        if (deadline is null)
            return (false, "Geen actieve registratie.");

        var windowStart = deadline.Value.AddMonths(-windowMonths);
        return today >= windowStart
            ? (true, $"Registratie verloopt binnen {windowMonths} maanden ({deadline:yyyy-MM-dd}).")
            : (false, $"Herregistratie kan vanaf {windowStart:yyyy-MM-dd}.");
    }

    /// <summary>Invariant: a non-active status must not carry a herregistratie date.</summary>
    public static bool IsStatusConsistent(RegistrationStatus s) =>
        s.Tag != StatusTag.Geregistreerd || s.HerregistratieDatum is not null;
}
