import { addDays, startOfDay } from "date-fns";
import { fromZonedTime, toZonedTime } from "date-fns-tz";
import type { OperationContext } from "@urql/core";

const timeZone = "Europe/Oslo";

// Global cache tag: any CMS content change purges everything
export const CMS_CACHE_TAG = "cms";

const MIN_REVALIDATE_SECONDS = 60;

// Clamped so a request just before midnight never yields revalidate ~0
export function secondsUntilOsloMidnight(now: Date = new Date()): number {
  const osloNow = toZonedTime(now, timeZone);
  const nextOsloMidnight = startOfDay(addDays(osloNow, 1));
  const instant = fromZonedTime(nextOsloMidnight, timeZone);
  return Math.max(
    Math.ceil((instant.getTime() - now.getTime()) / 1000),
    MIN_REVALIDATE_SECONDS
  );
}

// Per-operation contexts replace (not merge with) the client-default
// fetchOptions, so both contexts below are self-contained

// For per-user (search) and token-scoped (preview) queries
export const uncached: Partial<OperationContext> = {
  fetchOptions: { cache: "no-store" },
};

// For queries whose results depend on "today" (futureEvents, opening hours)
export function cachedUntilOsloMidnight(): Partial<OperationContext> {
  return {
    fetchOptions: {
      next: { revalidate: secondsUntilOsloMidnight(), tags: [CMS_CACHE_TAG] },
    },
  };
}
