"use server";

import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";

function generateCode(): string {
  const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  let code = "";
  for (let i = 0; i < 6; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return code;
}

export async function deleteStudent(formData: FormData) {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login");
  if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");

  const id = formData.get("id") as string;
  if (!id) return;

  const establishmentId = session.user.establishmentId;
  const student = await prisma.student.findFirst({
    where: {
      id,
      class: establishmentId ? { establishmentId } : undefined,
    },
  });
  if (!student) return;

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

  redirect("/dashboard/students");
}

export async function generateActivationCodeAction(formData: FormData) {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login");
  if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");

  const id = formData.get("id") as string;
  if (!id) return;

  const establishmentId = session.user.establishmentId;
  const student = await prisma.student.findFirst({
    where: {
      id,
      class: establishmentId ? { establishmentId } : undefined,
    },
  });

  if (!student) return;

  await prisma.student.update({
    where: { id },
    data: { activationCode: generateCode() },
  });

  redirect(`/dashboard/students/${id}`);
}
