const DEFAULT_TIMEZONE = "Europe/Madrid";

export function isValidTimezone(timezone: string): boolean {
  try {
    new Intl.DateTimeFormat("en-GB", { timeZone: timezone }).format(new Date());
    return true;
  } catch {
    return false;
  }
}

export function getApplicationTimezone(): string {
  const configured = (process.env.APP_TIMEZONE || process.env.SCRAPING_TIMEZONE || DEFAULT_TIMEZONE).trim();
  if (!isValidTimezone(configured)) {
    console.warn(`[Time] Zona horaria inválida "${configured}"; usando ${DEFAULT_TIMEZONE}`);
    return DEFAULT_TIMEZONE;
  }
  return configured;
}

export function formatLocalIso(date: Date, timezone = getApplicationTimezone()): string {
  const formatter = new Intl.DateTimeFormat("sv-SE", {
    timeZone: timezone,
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hourCycle: "h23",
  });
  return `${formatter.format(date).replace(" ", "T")} [${timezone}]`;
}

