"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "@/lib/db/client";
import { courses, enrollments } from "@/lib/db/schema";
import { requireUser } from "@/lib/auth/admin-guard";

const enrollSchema = z.object({ courseId: z.string().uuid() });

export async function enrollInCourse(formData: FormData) {
  const session = await requireUser();
  const userId = (session.user as { id?: string }).id;
  if (!userId) redirect("/login");

  const { courseId } = enrollSchema.parse({ courseId: formData.get("courseId") });

  const [course] = await db
    .select({ id: courses.id, status: courses.status })
    .from(courses)
    .where(eq(courses.id, courseId))
    .limit(1);
  if (!course || course.status !== "published") {
    redirect("/products/academy/courses");
  }

  const [existing] = await db
    .select({ userId: enrollments.userId })
    .from(enrollments)
    .where(and(eq(enrollments.courseId, courseId), eq(enrollments.userId, userId)))
    .limit(1);

  if (!existing) {
    await db.insert(enrollments).values({ userId, courseId });
  }

  revalidatePath("/account");
  redirect(`/account/academy/${courseId}`);
}
