"use server";

import { prisma } from "@/lib/db";
import { requireAuth, type ActionResult } from "@/lib/action-helpers";
import { revalidatePath } from "next/cache";


export async function setUserRole(userId: string, role: "admin" | "evaluator"): Promise<ActionResult> {
  const session = await requireAuth();
  if (!session || session.user.role !== "admin") return { success: false, error: "Accès refusé" };

  if (!role || !["admin", "evaluator"].includes(role)) {
    return { success: false, error: "Rôle invalide (admin | evaluator)" };
  }

  try {
    await prisma.user.update({ where: { id: userId }, data: { role } });
    revalidatePath("/admin");
    return { success: true };
  } catch (e) {
    console.error(e);
    return { success: false, error: "Erreur" };
  }
}

export async function deleteUser(userId: string): Promise<ActionResult> {
  const session = await requireAuth();
  if (!session || session.user.role !== "admin") return { success: false, error: "Accès refusé" };

  if (userId === session.user.id) {
    return { success: false, error: "Impossible de supprimer votre propre compte" };
  }

  try {
    await prisma.user.delete({ where: { id: userId } });
    revalidatePath("/admin");
    return { success: true };
  } catch (e) {
    console.error(e);
    return { success: false, error: "Erreur" };
  }
}
