/**
 * Staff session resolution using the staff-session JWT cookie.
 * This is separate from the main app auth (Clerk/NextAuth).
 * Only ADMIN and SUPER_ADMIN roles can access the staff dashboard.
 */

import { jwtVerify } from "jose";
import { cookies } from "next/headers";
import { prisma } from "./db";

const JWT_SECRET = new TextEncoder().encode(
  process.env.NEXTAUTH_SECRET || "fallback-secret-change-in-production",
);

export interface StaffUser {
  id: string;
  email: string;
  name: string;
  role: string;
  username?: string | null;
  isActive: boolean;
}

/**
 * Get current staff session from the staff-session JWT cookie.
 * Only returns users with ADMIN or SUPER_ADMIN role.
 */
export async function getStaffSession(): Promise<StaffUser | null> {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get("staff-session")?.value;

    if (!token) {
      return null;
    }

    // Verify JWT
    const { payload } = await jwtVerify(token, JWT_SECRET);

    if (!payload.id || !payload.email) {
      return null;
    }

    // Fetch user from database to get current state
    const user = await prisma.users.findFirst({
      where: {
        OR: [{ id: payload.id as string }, { email: payload.email as string }],
      },
      select: {
        id: true,
        email: true,
        name: true,
        username: true,
        role: true,
        isActive: true,
      },
    });

    if (!user) {
      return null;
    }

    // Only allow ADMIN and SUPER_ADMIN
    if (user.role !== "ADMIN" && user.role !== "SUPER_ADMIN") {
      return null;
    }

    if (!user.isActive) {
      return null;
    }

    return user;
  } catch (error) {
    console.error("Staff session verification error:", error);
    return null;
  }
}

/**
 * Validate staff session - alias for getStaffSession
 * Used by API routes to validate staff authentication
 * Returns the staff user if authenticated, null otherwise
 */
export async function validateStaffSession(
  _request?: unknown,
): Promise<StaffUser | null> {
  void _request;
  return getStaffSession();
}

/**
 * Clear staff session by deleting the staff-session cookie.
 */
export async function clearStaffSession() {
  const cookieStore = await cookies();
  cookieStore.delete("staff-session");
}
