"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 {
  enrollments,
  lessons,
  courseModules,
  lessonProgress,
} from "@/lib/db/schema";
import { requireUser } from "@/lib/auth/admin-guard";

const completeSchema = z.object({
  courseId: z.string().uuid(),
  lessonId: z.string().uuid(),
  next: z.string().optional(),
});

export async function markLessonComplete(formData: FormData) {
  const session = await requireUser();
  const userId = (session.user as { id?: string }).id!;
  const parsed = completeSchema.parse({
    courseId: formData.get("courseId"),
    lessonId: formData.get("lessonId"),
    next: formData.get("next") ?? undefined,
  });

  // Confirm enrolment.
  const [enrolled] = await db
    .select({ userId: enrollments.userId })
    .from(enrollments)
    .where(
      and(
        eq(enrollments.courseId, parsed.courseId),
        eq(enrollments.userId, userId),
      ),
    )
    .limit(1);
  if (!enrolled) redirect("/products/academy/courses");

  // Confirm lesson belongs to this course.
  const [lessonRow] = await db
    .select({ lessonId: lessons.id })
    .from(lessons)
    .innerJoin(courseModules, eq(courseModules.id, lessons.moduleId))
    .where(
      and(
        eq(lessons.id, parsed.lessonId),
        eq(courseModules.courseId, parsed.courseId),
      ),
    )
    .limit(1);
  if (!lessonRow) redirect(`/account/academy/${parsed.courseId}`);

  // Upsert progress row — primary key is (userId, lessonId).
  const [existing] = await db
    .select({ userId: lessonProgress.userId })
    .from(lessonProgress)
    .where(
      and(
        eq(lessonProgress.userId, userId),
        eq(lessonProgress.lessonId, parsed.lessonId),
      ),
    )
    .limit(1);
  if (!existing) {
    await db.insert(lessonProgress).values({
      userId,
      lessonId: parsed.lessonId,
    });
  }

  revalidatePath(`/account/academy/${parsed.courseId}`);
  revalidatePath(`/account/academy/${parsed.courseId}/${parsed.lessonId}`);
  if (parsed.next) {
    redirect(`/account/academy/${parsed.courseId}/${parsed.next}`);
  }
  redirect(`/account/academy/${parsed.courseId}`);
}
