/**
 * Date Validation Utilities
 *
 * Provides stage-aware start date validation for Business Profile.
 * Shared between Mongoose model and route handlers to ensure consistent rules.
 */

const STAGE_DATE_ERROR = 'Please select a valid start date for the selected business stage.';

/**
 * Compute valid date bounds for startDate based on the business stage.
 * Returns { minDate, maxDate } as YYYY-MM-DD strings.
 *
 * Rules:
 *   idea       → 6 months ago  to today + 3 months  (planning date, near future OK)
 *   mvp        → 2 years ago  to today + 6 months  (MVP in development, moderate future)
 *   early      → 5 years ago  to today             (already started, no future)
 *   growth     → 10 years ago to today             (operating, past only)
 *   scale      → 20 years ago to today             (scaling, past only)
 *   established → 1900-01-01    to today             (older/past only)
 */
export function getStageDateBounds(stage: string): { minDate: string; maxDate: string } {
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const fmt = (d: Date): string => {
    const yyyy = d.getFullYear().toString().padStart(4, '0');
    const mm = (d.getMonth() + 1).toString().padStart(2, '0');
    const dd = d.getDate().toString().padStart(2, '0');
    return `${yyyy}-${mm}-${dd}`;
  };

  const addMonths = (date: Date, months: number): Date => {
    const result = new Date(date);
    result.setMonth(result.getMonth() + months);
    return result;
  };

  const ABSOLUTE_MIN = '1900-01-01';
  const todayStr = fmt(today);

  /**
   * Mirrors the client rule: every stage can reach back to 1990. The short
   * windows ('idea' is six months) otherwise pinned the picker to the current
   * year. This MUST match the frontend copy in
   * modules/foundation/business-profile/page.tsx — if the picker offers a date
   * the server then rejects, the save fails after the form has passed.
   */
  const EARLIEST_SELECTABLE = '1990-01-01';
  const widen = (b: { minDate: string; maxDate: string }) => ({
    ...b,
    minDate: b.minDate < EARLIEST_SELECTABLE ? b.minDate : EARLIEST_SELECTABLE,
  });

  switch (stage) {
    case 'idea':
      return widen({ minDate: fmt(addMonths(today, -6)), maxDate: fmt(addMonths(today, 3)) });
    case 'mvp':
      return widen({ minDate: fmt(addMonths(today, -24)), maxDate: fmt(addMonths(today, 6)) });
    case 'early':
      return widen({ minDate: fmt(addMonths(today, -60)), maxDate: todayStr });
    case 'growth':
      return widen({ minDate: fmt(addMonths(today, -120)), maxDate: todayStr });
    case 'scale':
      return widen({ minDate: fmt(addMonths(today, -240)), maxDate: todayStr });
    case 'established':
      return { minDate: ABSOLUTE_MIN, maxDate: todayStr };
    default:
      return { minDate: ABSOLUTE_MIN, maxDate: fmt(addMonths(today, 3)) };
  }
}

/**
 * Validate that a startDate is within the allowed bounds for the given business stage.
 * Returns null if valid, or the error message string if invalid.
 * If startDate is empty/undefined, returns null (field is optional).
 */
export function validateStartDateForStage(startDate: string | undefined, stage: string): string | null {
  if (!startDate || startDate.trim() === '') return null; // optional field — empty is valid

  const bounds = getStageDateBounds(stage);
  if (startDate < bounds.minDate || startDate > bounds.maxDate) {
    return STAGE_DATE_ERROR;
  }
  return null;
}