import { NextResponse } from "next/server";

const IS_PROD = process.env.NODE_ENV === "production";

export const ACCESS_COOKIE = "ledgerone_access";
export const REFRESH_COOKIE = "ledgerone_refresh";
export const AUTH_COOKIE = "ledgerone_auth";
export const NONCE_COOKIE = "ledgerone_nonce";

const cookieOptions = {
  httpOnly: true,
  secure: IS_PROD,
  sameSite: "lax" as const,
  path: "/",
};

export function setAuthCookies(res: NextResponse, accessToken: string, refreshToken: string, sessionNonce?: string) {
  res.cookies.set(ACCESS_COOKIE, accessToken, {
    ...cookieOptions,
    maxAge: 60,
  });
  res.cookies.set(REFRESH_COOKIE, refreshToken, {
    ...cookieOptions,
    maxAge: 30 * 24 * 60 * 60,
  });
  res.cookies.set(AUTH_COOKIE, "1", {
    ...cookieOptions,
    maxAge: 30 * 24 * 60 * 60,
  });
  if (sessionNonce) {
    res.cookies.set(NONCE_COOKIE, sessionNonce, {
      ...cookieOptions,
      maxAge: 30 * 24 * 60 * 60,
    });
  }
}

export function clearAuthCookies(res: NextResponse) {
  for (const name of [ACCESS_COOKIE, REFRESH_COOKIE, AUTH_COOKIE, NONCE_COOKIE]) {
    res.cookies.set(name, "", {
      ...cookieOptions,
      maxAge: 0,
    });
  }
}
