import { jwtVerify, SignJWT } from "jose";
import { cookies } from "next/headers";
import { redirect } from "@/i18n/navigation";
import type { Locale } from "@/i18n/routing";

const COOKIE_NAME = "rizz_admin_session";

function getSecret() {
  const s =
    process.env.AUTH_SECRET ?? "dev-only-change-in-production-32chars";
  if (
    process.env.NODE_ENV === "production" &&
    (!process.env.AUTH_SECRET || process.env.AUTH_SECRET.length < 16)
  ) {
    throw new Error("AUTH_SECRET must be set in production (min 16 characters)");
  }
  return new TextEncoder().encode(s);
}

export async function createAdminSessionToken() {
  return new SignJWT({ role: "admin" })
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime("7d")
    .sign(getSecret());
}

export async function verifyAdminSessionToken(token: string) {
  try {
    const { payload } = await jwtVerify(token, getSecret());
    return payload.role === "admin";
  } catch {
    return false;
  }
}

export async function getIsAdmin() {
  try {
    const token = (await cookies()).get(COOKIE_NAME)?.value;
    if (!token) return false;
    return verifyAdminSessionToken(token);
  } catch {
    return false;
  }
}

export async function requireAdmin(locale: Locale) {
  if (!(await getIsAdmin())) {
    redirect({ href: "/admin/login", locale });
  }
}

export const ADMIN_SESSION_COOKIE = COOKIE_NAME;
