const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
const ISO_DATE_PREFIX_PATTERN = /^(\d{4}-\d{2}-\d{2})T/;

export function normalizeDateOnly(value?: string | null): string | null | undefined {
  if (value == null || value === '') return value;
  if (DATE_ONLY_PATTERN.test(value)) return value;

  const isoPrefix = ISO_DATE_PREFIX_PATTERN.exec(value)?.[1];
  if (isoPrefix) {
    const date = new Date(value);
    if (!Number.isNaN(date.getTime())) return date.toISOString().slice(0, 10);
  }

  throw new Error(`无效日期格式: ${value}`);
}
