import { NextResponse } from "next/server";

export type CacheDuration = "short" | "medium" | "long" | "none";

const CACHE_DURATIONS: Record<CacheDuration, number> = {
  short: 60, // 1 minute
  medium: 300, // 5 minutes
  long: 3600, // 1 hour
  none: 0,
};

/**
 * Sets appropriate cache headers for a response.
 * 
 * @param response - The NextResponse to add headers to
 * @param duration - Cache duration preset or custom seconds
 * @param isPublic - Whether the response can be cached by public caches
 * @returns The response with cache headers
 */
export function setCacheHeaders(
  response: NextResponse,
  duration: CacheDuration | number = "medium",
  isPublic: boolean = true,
): NextResponse {
  const seconds = typeof duration === "number" ? duration : CACHE_DURATIONS[duration];

  if (seconds === 0) {
    // No cache
    response.headers.set("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");
    response.headers.set("Pragma", "no-cache");
    response.headers.set("Expires", "0");
  } else {
    // Cache with specified duration
    const cacheControl = isPublic
      ? `public, max-age=${seconds}, s-maxage=${seconds}, stale-while-revalidate=${seconds * 2}`
      : `private, max-age=${seconds}, stale-while-revalidate=${seconds * 2}`;
    
    response.headers.set("Cache-Control", cacheControl);
    
    // Set Expires header for older clients
    const expires = new Date(Date.now() + seconds * 1000);
    response.headers.set("Expires", expires.toUTCString());
  }

  return response;
}

/**
 * Creates a response with cache headers applied.
 * Useful for wrapping existing response creation.
 */
export function cachedResponse<T>(
  data: T,
  duration: CacheDuration | number = "medium",
  isPublic: boolean = true,
  init?: ResponseInit,
): NextResponse {
  const response = NextResponse.json(data, init);
  return setCacheHeaders(response, duration, isPublic);
}

