import { SignJWT, jwtVerify } from "jose";

const encoder = new TextEncoder();

/** Secret par défaut uniquement pour le dev local — définissez AUTH_SECRET en prod. */
const DEV_FALLBACK =
  "dev-secret-change-me-in-production-min-32-chars-required!!";

export function getJwtSecretKey() {
  const secret = process.env.AUTH_SECRET ?? DEV_FALLBACK;
  return encoder.encode(secret);
}

export async function createSessionToken(userId: string): Promise<string> {
  return new SignJWT({ sub: userId })
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime("7d")
    .sign(getJwtSecretKey());
}

export async function verifySessionToken(
  token: string
): Promise<string | null> {
  try {
    const { payload } = await jwtVerify(token, getJwtSecretKey());
    return typeof payload.sub === "string" ? payload.sub : null;
  } catch {
    return null;
  }
}

export const SESSION_COOKIE = "gauffre_session";
