import type { DayOfWeek } from '@repo/api-contract';

export function toIsoDateLocal(date: Date) {
  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}`;
}

export function fromIsoDateLocal(dateIso: string): Date | undefined {
  const [year, month, day] = dateIso.split('-').map(Number);
  if (!year || !month || !day) return undefined;
  return new Date(year, month - 1, day);
}

export function timeToMinutes(time: string) {
  const [hours, minutes] = time.split(':').map(Number);
  return hours * 60 + minutes;
}

export function minutesToTime(minutes: number) {
  const hours = Math.floor(minutes / 60);
  const remainder = minutes % 60;
  return `${String(hours).padStart(2, '0')}:${String(remainder).padStart(2, '0')}`;
}

export function addDaysIso(dateIso: string, amount: number) {
  const date = fromIsoDateLocal(dateIso) ?? new Date();
  date.setDate(date.getDate() + amount);
  return toIsoDateLocal(date);
}

export function isTodayIso(dateIso: string) {
  return dateIso === toIsoDateLocal(new Date());
}

export function formatBookingDate(dateIso: string, options?: Intl.DateTimeFormatOptions) {
  const date = fromIsoDateLocal(dateIso);
  if (!date) return dateIso;

  return new Intl.DateTimeFormat('es-AR', {
    weekday: 'long',
    day: '2-digit',
    month: 'long',
    year: options?.year,
    ...options,
  }).format(date);
}

export function getDayOfWeek(dateIso: string): DayOfWeek {
  const date = fromIsoDateLocal(dateIso) ?? new Date();
  const day = date.getDay();

  if (day === 0) return 'SUNDAY';
  if (day === 1) return 'MONDAY';
  if (day === 2) return 'TUESDAY';
  if (day === 3) return 'WEDNESDAY';
  if (day === 4) return 'THURSDAY';
  if (day === 5) return 'FRIDAY';
  return 'SATURDAY';
}

export function getNowTime() {
  const now = new Date();
  return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
}
