'use server';

import { z } from "zod";
import { prisma } from "@/lib/prisma";
import { hashPassword } from "@/lib/auth";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
import { revalidatePath } from "next/cache";

const createUserSchema = z.object({
  email: z.string().email("Email invalide"),
  password: z.string().min(8, "Le mot de passe doit faire au moins 8 caractères"),
  role: z.enum(["admin", "teacher"], { message: "Rôle invalide" }),
  establishmentId: z.string().optional().nullable(),
});

export async function createUser(formData: FormData) {
  const session = await getServerSession(authOptions);
  if (!session?.user) throw new Error("Non authentifié");

  const isSuperadmin = session.user.role === "superadmin";
  if (!isSuperadmin && session.user.role !== "admin") throw new Error("Accès interdit");

  const raw = Object.fromEntries(formData);
  const parsed = createUserSchema.safeParse(raw);
  if (!parsed.success) {
    throw new Error(parsed.error.issues.map((e: any) => e.message).join(", "));
  }

  const { email, password, role, establishmentId } = parsed.data;

  const finalEstablishmentId = isSuperadmin
    ? (establishmentId || null)
    : session.user.establishmentId;

  const existing = await prisma.user.findUnique({ where: { email } });
  if (existing) throw new Error("Cet email est déjà utilisé");

  const hashed = await hashPassword(password);

  await prisma.user.create({
    data: {
      email,
      password: hashed,
      role,
      establishmentId: finalEstablishmentId,
    },
  });

  revalidatePath("/dashboard/users");
  redirect("/dashboard/users");
}

export async function deleteUser(userId: string) {
  const session = await getServerSession(authOptions);
  if (!session?.user) throw new Error("Non authentifié");

  const isSuperadmin = session.user.role === "superadmin";
  if (!isSuperadmin && session.user.role !== "admin") throw new Error("Accès interdit");

  if (userId === session.user.id) throw new Error("Vous ne pouvez pas supprimer votre propre compte");

  const user = await prisma.user.findUnique({ where: { id: userId } });
  if (!user) throw new Error("Utilisateur introuvable");

  if (!isSuperadmin && user.establishmentId !== session.user.establishmentId) {
    throw new Error("Accès interdit");
  }

  await prisma.user.delete({ where: { id: userId } });

  revalidatePath("/dashboard/users");
  redirect("/dashboard/users");
}
