import { FLOCK_VALIDATION_MESSAGES } from "@/lib/constants/flock-limits";
import {
  defaultMothershipReadyDateIso,
  isMothershipWeekendIso,
  parseIsoDateLocal,
  snapMothershipReadyDateToWeekday,
  toIsoDateLocal,
} from "@/lib/mothership/logged-in-constraints";

const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const ISO_DATE_CAPTURE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
const DISPLAY_DATE_RE = /^(\d{2})\/(\d{2})\/(\d{4})$/;

/** 本地日历最早可选日：今天（若为周末则拨到周一），PRD §14.3 */
export function minFlockPickupDateIso(): string {
  return defaultMothershipReadyDateIso();
}

export function flockPickupIsoFromDisplay(display: string): string | null {
  const trimmed = display.trim();
  const m = DISPLAY_DATE_RE.exec(trimmed);
  if (!m) return null;
  return `${m[3]}-${m[1]}-${m[2]}`;
}

export function isFlockPickupDateOnOrAfterToday(iso: string): boolean {
  if (!ISO_DATE_RE.test(iso)) return false;
  return iso >= minFlockPickupDateIso();
}

export function flockPickupDateValidationMessageFromIso(
  iso: string,
): string | null {
  if (!iso.trim()) {
    return FLOCK_VALIDATION_MESSAGES.pickupDate;
  }
  if (!ISO_DATE_RE.test(iso)) {
    return FLOCK_VALIDATION_MESSAGES.pickupDate;
  }
  if (!isFlockPickupDateOnOrAfterToday(iso)) {
    return FLOCK_VALIDATION_MESSAGES.pickupDateTooEarly;
  }
  if (isMothershipWeekendIso(iso)) {
    return FLOCK_VALIDATION_MESSAGES.pickupDateWeekend;
  }
  return null;
}

export function flockPickupDateValidationMessageFromDisplay(
  display: string,
): string | null {
  if (!DISPLAY_DATE_RE.test(display.trim())) {
    return FLOCK_VALIDATION_MESSAGES.pickupDate;
  }
  const iso = flockPickupIsoFromDisplay(display);
  if (!iso) {
    return FLOCK_VALIDATION_MESSAGES.pickupDate;
  }
  if (!isFlockPickupDateOnOrAfterToday(iso)) {
    return FLOCK_VALIDATION_MESSAGES.pickupDateTooEarly;
  }
  if (isMothershipWeekendIso(iso)) {
    return FLOCK_VALIDATION_MESSAGES.pickupDateWeekend;
  }
  return null;
}

export function flockPickupDisplayFromIso(iso: string): string {
  const m = ISO_DATE_CAPTURE_RE.exec(iso.trim());
  if (!m) return iso;
  return `${m[2]}/${m[3]}/${m[1]}`;
}

/** 表单默认取货日：最早可选日的下一工作日 */
export function defaultFlockPickupDateIso(): string {
  const min = parseIsoDateLocal(minFlockPickupDateIso()) ?? new Date();
  min.setDate(min.getDate() + 1);
  return snapMothershipReadyDateToWeekday(toIsoDateLocal(min));
}
