import { toZonedTime, format } from "date-fns-tz";

/**
 * Convert a Date or ISO string to Asia/Kolkata time and return formatted string.
 * @param date Date object or ISO string
 * @param fmt Output format (default: 'yyyy-MM-dd HH:mm:ss')
 */
export function toKolkataTime(
  date: Date | string,
  fmt = "yyyy-MM-dd hh:mm:ss a",
) {
  const tz = "Asia/Kolkata";
  const d = typeof date === "string" ? new Date(date) : date;
  const zoned = toZonedTime(d, tz);
  return format(zoned, fmt, { timeZone: tz });
}

/**
 * Get the current time in Asia/Kolkata as a Date object.
 */
export function getIndiaNow(): Date {
  return toZonedTime(new Date(), "Asia/Kolkata");
}

/**
 * Get the current time in Asia/Kolkata as an ISO string.
 */
export function indiaNowISOString(): string {
  return new Date().toLocaleString('sv-SE', { timeZone: 'Asia/Kolkata' });
}

const IST_OFFSET_MS = 5.5 * 60 * 60 * 1000;

/**
 * Parse a wall-clock "yyyy-MM-dd HH:mm:ss" (or with 'T' separator) string that
 * represents Asia/Kolkata local time into the equivalent UTC Date. IST has a
 * fixed +05:30 offset (no DST), so this is a plain arithmetic shift.
 */
export function fromKolkataTime(dateStr: string): Date {
  const match = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})$/.exec(dateStr.trim());
  if (!match) throw new Error('Invalid timestamp format, expected "yyyy-MM-dd HH:mm:ss"');

  const [, year, month, day, hour, minute, second] = match;
  const utcMillis =
    Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), Number(second)) -
    IST_OFFSET_MS;

  return new Date(utcMillis);
}
