import "server-only";

import { redirect } from "next/navigation";
import { UserRole } from "@prisma/client";
import { getSessionPayload } from "@/lib/auth/session";
import { getCurrentUser } from "@/lib/auth/user";
import { prisma } from "@/lib/prisma";

function parseAdminEmails() {
  const raw = process.env.ADMIN_EMAILS ?? "";

  return new Set(
    raw
      .split(",")
      .map((email) => email.trim().toLowerCase())
      .filter(Boolean),
  );
}

export function isConfiguredAdminEmail(email: string) {
  return parseAdminEmails().has(email.toLowerCase());
}

export function isAdminIdentity(email: string, role: UserRole) {
  return role === UserRole.ADMIN || isConfiguredAdminEmail(email);
}

export async function requireAdminUser() {
  const user = await getCurrentUser();

  if (!user || !isAdminIdentity(user.email, user.role)) {
    redirect("/dashboard?error=admin_required");
  }

  return user;
}

export async function requireAdminApiUser() {
  const session = await getSessionPayload();

  if (!session) {
    return null;
  }

  const user = await prisma.user.findUnique({
    where: { id: session.userId },
    select: {
      id: true,
      email: true,
      role: true,
      name: true,
      emailVerifiedAt: true,
    },
  });

  if (!user || !isAdminIdentity(user.email, user.role)) {
    return null;
  }

  return user;
}
