/**
 * Materials 页面的日期范围筛选解析与格式化。
 *
 * 输入支持的格式：
 *   - "20260101"               → 单天起点
 *   - "20260101-20260201"      → 双向区间
 *   - "-20260201"              → 仅终点
 *   - "20260101-"              → 仅起点
 */

export function normalizeCompactDate(value: string): string {
  if (!/^\d{8}$/.test(value)) return '';
  const year = Number(value.slice(0, 4));
  const month = Number(value.slice(4, 6));
  const day = Number(value.slice(6, 8));
  const date = new Date(year, month - 1, day);
  if (
    Number.isNaN(date.getTime())
    || date.getFullYear() !== year
    || date.getMonth() !== month - 1
    || date.getDate() !== day
  ) {
    return '';
  }
  return `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}`;
}

export function parseCreatedAtRange(value: string): { from: string; to: string } | null {
  const trimmed = value.trim();
  if (!trimmed) return { from: '', to: '' };
  if (!/^[\d-]+$/.test(trimmed)) return null;

  const [rawFrom = '', rawTo = ''] = trimmed.split('-', 2);
  if (!rawFrom && !rawTo) return { from: '', to: '' };

  const from = rawFrom ? normalizeCompactDate(rawFrom) : '';
  const to = rawTo ? normalizeCompactDate(rawTo) : '';

  if ((rawFrom && !from) || (rawTo && !to)) return null;
  return { from, to };
}

export function toCompactDate(value: string): string {
  return value.replace(/-/g, '');
}

export function formatCreatedAtRangeValue(from: string, to: string): string {
  if (from && to) return `${toCompactDate(from)}-${toCompactDate(to)}`;
  if (from) return toCompactDate(from);
  if (to) return `-${toCompactDate(to)}`;
  return '';
}

export function parseDateValue(value: string): Date | undefined {
  if (!value) return undefined;
  const [year, month, day] = value.split('-').map(Number);
  if (!year || !month || !day) return undefined;
  const date = new Date(year, month - 1, day);
  if (
    Number.isNaN(date.getTime())
    || date.getFullYear() !== year
    || date.getMonth() !== month - 1
    || date.getDate() !== day
  ) {
    return undefined;
  }
  return date;
}

export function formatDateForFilter(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
