import { NextRequest } from "next/server";
import { getServerSession } from "next-auth";
import { db } from "@/lib/db";
import { authOptions } from "@/lib/auth";

export async function getApiUser(req: NextRequest) {
  const authHeader = req.headers.get("authorization");
  const bearerToken = authHeader?.match(/^Bearer\s+(.+)$/i)?.[1];

  if (bearerToken) {
    const session = await db.session.findUnique({
      where: { sessionToken: bearerToken },
      include: { user: true },
    });

    if (session && session.expires > new Date()) {
      return session.user;
    }
  }

  const session = await getServerSession(authOptions);
  const userId = (session?.user as any)?.id;
  if (!userId) return null;

  return db.user.findUnique({ where: { id: userId } });
}

export async function requireApiAdmin(req: NextRequest) {
  const user = await getApiUser(req);
  if (!user || user.role !== "ADMIN") return null;
  return user;
}
