import type { Office } from "@/lib/types";

/**
 * Division schedules are wall-clock times in the employee's office timezone
 * (e.g. 08:00 WITA for an office in Bali), so anything compared to them or
 * shown next to them uses the office's timezone, not the device's.
 */
export const DEFAULT_TIMEZONE = "Asia/Jakarta";
export const DEFAULT_TIMEZONE_LABEL = "WIB";

export interface OfficeTimezone {
  timeZone: string;
  label: string;
}

export function officeTimezone(office: Office | null | undefined): OfficeTimezone {
  return {
    timeZone: office?.timezone ?? DEFAULT_TIMEZONE,
    label: office?.timezone_label ?? DEFAULT_TIMEZONE_LABEL,
  };
}

export interface ZonedParts {
  year: number;
  /** 1–12. */
  month: number;
  day: number;
  hour: number;
  minute: number;
  second: number;
  /** ISO weekday: 1 = Monday … 7 = Sunday. */
  isoWeekday: number;
}

/** The calendar date and clock time `date` shows in `timeZone`. */
export function zonedParts(date: Date, timeZone: string): ZonedParts {
  const parts = Object.fromEntries(
    new Intl.DateTimeFormat("en-US", {
      timeZone,
      hourCycle: "h23",
      year: "numeric",
      month: "numeric",
      day: "numeric",
      hour: "numeric",
      minute: "numeric",
      second: "numeric",
    })
      .formatToParts(date)
      .map((part) => [part.type, part.value]),
  );
  const year = Number(parts.year);
  const month = Number(parts.month);
  const day = Number(parts.day);
  const weekday = new Date(Date.UTC(year, month - 1, day)).getUTCDay();

  return {
    year,
    month,
    day,
    hour: Number(parts.hour),
    minute: Number(parts.minute),
    second: Number(parts.second),
    isoWeekday: weekday === 0 ? 7 : weekday,
  };
}

/**
 * The instant at which the clock in `timeZone` shows `hours:minutes` on the
 * same calendar day as `reference` does there.
 */
export function zonedTimeOnSameDay(reference: Date, hours: number, minutes: number, timeZone: string): Date {
  const local = zonedParts(reference, timeZone);
  const asUtc = Date.UTC(local.year, local.month - 1, local.day, local.hour, local.minute, local.second);
  const offsetMs = asUtc - Math.floor(reference.getTime() / 1000) * 1000;
  return new Date(Date.UTC(local.year, local.month - 1, local.day, hours, minutes, 0, 0) - offsetMs);
}

/** A "Y-M-D" key of `date`'s calendar day in `timeZone`, for same-day comparisons. */
export function zonedDateKey(date: Date, timeZone: string): string {
  const { year, month, day } = zonedParts(date, timeZone);
  return `${year}-${month}-${day}`;
}
