import { format, startOfDay, endOfDay } from 'date-fns';
import { utcToZonedTime, zonedTimeToUtc } from 'date-fns-tz';

const DEFAULT_TIMEZONE = 'Asia/Shanghai';

/**
 * 获取指定时区的一天开始时间
 */
export function startOfDayInTimezone(date: Date, timezone: string = DEFAULT_TIMEZONE): Date {
  const zonedDate = utcToZonedTime(date, timezone);
  const start = startOfDay(zonedDate);
  return zonedTimeToUtc(start, timezone);
}

/**
 * 获取指定时区的一天结束时间
 */
export function endOfDayInTimezone(date: Date, timezone: string = DEFAULT_TIMEZONE): Date {
  const zonedDate = utcToZonedTime(date, timezone);
  const end = endOfDay(zonedDate);
  return zonedTimeToUtc(end, timezone);
}

/**
 * 格式化为日期Key (YYYY-MM-DD)
 */
export function formatToDateKey(date: Date, timezone: string = DEFAULT_TIMEZONE): string {
  const zonedDate = utcToZonedTime(date, timezone);
  return format(zonedDate, 'yyyy-MM-dd');
}
