/**
 * Date utilities for billing period calculations
 */

/**
 * Calculate period end date safely, avoiding month overflow.
 *
 * JavaScript's Date.setMonth() has edge cases: Jan 31 + 1 month = Mar 3 (not Feb 28).
 * This function caps at the last day of the target month.
 *
 * @param from - Period start date
 * @param cycle - Billing cycle ('monthly' or 'annual')
 * @returns Period end date
 */
export function calculatePeriodEnd(from: Date, cycle: 'monthly' | 'annual'): Date {
  const result = new Date(from);

  if (cycle === 'monthly') {
    const originalDay = result.getDate();
    result.setDate(1); // Avoid overflow when advancing month
    result.setMonth(result.getMonth() + 1);
    // Cap at last day of target month
    const lastDay = new Date(result.getFullYear(), result.getMonth() + 1, 0).getDate();
    result.setDate(Math.min(originalDay, lastDay));
  } else {
    result.setFullYear(result.getFullYear() + 1);
  }

  return result;
}
