import type { NextAuthConfig } from "next-auth";

// Edge-safe auth config — no native modules (no argon2, no prisma).
// Used by auth-edge.ts (middleware) to verify JWT sessions without
// pulling in Node.js-only packages into the Edge runtime.

// Secure cookies whenever the deployment URL is https, not only when
// NODE_ENV === "production". Staging over HTTPS must also ship Secure
// cookies, otherwise the session token is MITM-interceptable. The check
// happens at module-eval time — that's fine because the AUTH_URL / Next.js
// deployment URL does not change between requests.
function isHttpsDeployment(): boolean {
  const explicit = (process.env["AUTH_URL"] ?? process.env["NEXTAUTH_URL"] ?? "").trim();
  if (explicit.startsWith("https://")) return true;
  // Vercel sets VERCEL=1 and the URL is always https there.
  if (process.env["VERCEL"] === "1") return true;
  return false;
}

const useSecure = isHttpsDeployment();

// Cookie name with __Host- prefix when secure. The __Host- prefix is an
// additional browser-enforced hardening (RFC 6265bis §4.1.3.2) that only
// accepts the cookie if Secure=true, Path="/", and no Domain attribute —
// preventing subdomain takeover from rewriting the session cookie.
const cookiePrefix = useSecure ? "__Host-" : "";

const baseCookieOptions = {
  httpOnly: true,
  sameSite: "strict" as const,
  path: "/",
  secure: useSecure,
};

export const authConfig = {
  pages: {
    signIn: "/auth/signin",
  },
  providers: [],
  session: {
    strategy: "jwt",
    maxAge: 28800, // 8 hours absolute timeout
    updateAge: 1800, // refresh token every 30 minutes
  },
  cookies: {
    sessionToken: {
      name: `${cookiePrefix}authjs.session-token`,
      options: baseCookieOptions,
    },
    callbackUrl: {
      name: `${cookiePrefix}authjs.callback-url`,
      options: baseCookieOptions,
    },
    csrfToken: {
      name: `${cookiePrefix}authjs.csrf-token`,
      options: baseCookieOptions,
    },
  },
} satisfies NextAuthConfig;
