import { Formatting } from "@customer-portal/domain/toolkit";

const INVALID_DATE = "Invalid date";

export type FormatDateFallbackOptions = {
  fallback?: string | undefined;
  locale?: string | undefined;
  dateStyle?: "short" | "medium" | "long" | "full" | undefined;
  timeStyle?: "short" | "medium" | "long" | "full" | undefined;
  includeTime?: boolean | undefined;
  timezone?: string | undefined;
};

export function formatIsoDate(
  iso: string | null | undefined,
  options: FormatDateFallbackOptions = {}
): string {
  const {
    fallback = "N/A",
    locale,
    dateStyle = "medium",
    timeStyle = "short",
    includeTime = false,
    timezone,
  } = options;

  if (!iso) return fallback;
  if (!Formatting.isValidDate(iso)) return INVALID_DATE;

  return Formatting.formatDate(iso, {
    locale: locale ?? undefined,
    dateStyle,
    timeStyle,
    includeTime,
    timezone,
  });
}

export function formatIsoRelative(
  iso: string | null | undefined,
  options: { fallback?: string | undefined; locale?: string | undefined } = {}
): string {
  const { fallback = "N/A", locale } = options;
  if (!iso) return fallback;
  if (!Formatting.isValidDate(iso)) return INVALID_DATE;
  return Formatting.formatRelativeDate(iso, { locale: locale ?? undefined });
}

export function formatIsoMonthDay(
  iso: string | null | undefined,
  options: { fallback?: string | undefined; locale?: string | undefined } = {}
): string {
  const { fallback = "N/A", locale = "en-US" } = options;
  if (!iso) return fallback;
  if (!Formatting.isValidDate(iso)) return INVALID_DATE;
  try {
    const date = new Date(iso);
    return date.toLocaleDateString(locale, { month: "short", day: "numeric" });
  } catch {
    return INVALID_DATE;
  }
}

export function isSameDay(a: Date, b: Date): boolean {
  return (
    a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate()
  );
}

export function isToday(date: Date, now: Date = new Date()): boolean {
  return isSameDay(date, now);
}

export function isYesterday(date: Date, now: Date = new Date()): boolean {
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  return isSameDay(date, yesterday);
}
