// /app/api/enrollments/route.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// --- GET --------------------------------------------------------------------

export async function GET() {
  try {
    const enrollments = await prisma.enrollment.findMany({
      include: {
        user: { select: { id: true, name: true, email: true } },
        course: { select: { id: true, title: true, code: true, } },
      },
      orderBy: { createdAt: 'asc' },
    });
    return NextResponse.json(enrollments);
  } catch (err) {
    console.error('GET /api/enrollments error', err);
    return NextResponse.json({ error: 'Failed to fetch enrollments' }, { status: 500 });
  }
}

// --- POST --------------------------------------------------------------------

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();

    // incoming payload example:
    // { userId: "cmicsu2030000uaec0sp56gso", courseId: "cmicrx1b70000uahwilu0gh9u", role: "student" }
    const userId: string | undefined = body.userId;
    const courseId: string | undefined = body.courseId;
    // const role: string = body.role ?? 'student';

    if (!userId || !courseId) {
      return NextResponse.json({ error: 'Missing userId or courseId' }, { status: 400 });
    }

    // Optional: Prevent duplicate enrolments
    const existing = await prisma.enrollment.findFirst({
      where: { userId: userId, courseId: courseId },
    });

    if (existing) {
      return NextResponse.json(
        { error: 'Enrollment already exists' },
        { status: 409 }
      );
    }

    // Create enrollment using STRING IDs
    const enrollment = await prisma.enrollment.create({
      data: {
        user: { connect: { id: userId } },
        course: { connect: { id: courseId } },
        // role: role,
      },
      include: {
        user: { select: { id: true, name: true, email: true } },
        course: { select: { id: true, title: true } },
      },
    });

    return NextResponse.json(enrollment, { status: 201 });
  } catch (err) {
    console.error('POST /api/enrollments error', err);
    return NextResponse.json({ error: 'Failed to create enrollment' }, { status: 500 });
  }
}

// --- DELETE --------------------------------------------------------------------

export async function DELETE(req: NextRequest) {
  try {
    const body = await req.json();
    const id = body?.id;

    if (!id) {
      return NextResponse.json({ error: 'Missing id' }, { status: 400 });
    }

    await prisma.enrollment.delete({
      where: { id: id }, // STRING — not Number(id)
    });

    return NextResponse.json({ success: true });
  } catch (err) {
    console.error('DELETE /api/enrollments error', err);
    return NextResponse.json({ error: 'Failed to delete enrollment' }, { status: 500 });
  }
}
