// ../preview-next/src/session.ts
import { cookies } from "next/headers.js";
import { cache } from "react";

// ../preview-next/src/auth-contract.ts
function resolvePreviewAuthMode(previewAuthModeClaim) {
  return previewAuthModeClaim === "onboardingGrant" ? "onboardingGrant" : "userSession";
}
function resolvePreviewSessionCanEdit(input) {
  return input.authMode === "userSession" && input.canEdit;
}
function resolvePreviewRuntimeSession(input) {
  if (input.authMode === "onboardingGrant") {
    return {
      kind: "onboardingGrant",
      expiresAt: input.expiresAt
    };
  }
  if (input.authMode !== "userSession") {
    return null;
  }
  return {
    kind: "userSession",
    canEdit: input.canEdit,
    canManage: input.canManage,
    expiresAt: input.expiresAt
  };
}

// ../preview-next/src/constants.ts
var PREVIEW_COOKIE_NAME = "preview_token";
var PREVIEW_COOKIE_MAX_AGE = 60 * 60 * 12;

// ../preview-next/src/jwt.ts
function base64UrlDecodeToString(value) {
  const normalized = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
  if (typeof globalThis.atob === "function") {
    const binary = globalThis.atob(normalized);
    const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
    return new TextDecoder().decode(bytes);
  }
  return Buffer.from(normalized, "base64").toString("utf8");
}
function decodeJwtPayload(token) {
  const parts = token.split(".");
  if (parts.length < 2) return null;
  const payloadPart = parts[1];
  if (!payloadPart) return null;
  try {
    const payload = base64UrlDecodeToString(payloadPart);
    return JSON.parse(payload);
  } catch {
    return null;
  }
}

// ../preview-next/src/session.ts
async function validatePreviewSessionToken(token) {
  if (!token) {
    return {
      status: "absent",
      token: null,
      expiresAt: null,
      canEdit: false,
      authMode: null,
      runtimeSession: null
    };
  }
  const payload = decodeJwtPayload(token);
  if (!payload || typeof payload.exp !== "number") {
    return {
      status: "invalid",
      token,
      expiresAt: null,
      canEdit: false,
      authMode: null,
      runtimeSession: null
    };
  }
  const authMode = resolvePreviewAuthMode(
    payload.preview_auth_mode
  );
  const expiresAtMs = payload.exp * 1e3;
  const expiresAt = new Date(expiresAtMs).toISOString();
  const now = Date.now();
  if (expiresAtMs <= now) {
    return {
      status: "expired",
      token,
      expiresAt,
      canEdit: false,
      authMode,
      runtimeSession: null
    };
  }
  const canEdit = resolvePreviewSessionCanEdit({
    authMode,
    canEdit: payload.can_edit !== false
  });
  const runtimeSession = resolvePreviewRuntimeSession({
    authMode,
    canEdit,
    canManage: payload.can_manage_site === true,
    expiresAt
  });
  return {
    status: "valid",
    token,
    expiresAt,
    // Dashboard-backed preview sessions use real auth access tokens, which do
    // not reliably carry an explicit `can_edit: true` claim. Absence means the
    // normal editable user-session path; only an explicit `false` should
    // downgrade the session.
    canEdit,
    authMode,
    runtimeSession
  };
}
async function readPreviewSession(cookiesStore) {
  const token = cookiesStore.get(PREVIEW_COOKIE_NAME)?.value ?? null;
  return validatePreviewSessionToken(token);
}
var getPreviewSession = cache(async () => {
  const cookieStore = await cookies();
  return readPreviewSession(cookieStore);
});
export {
  getPreviewSession,
  readPreviewSession,
  validatePreviewSessionToken
};
