import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { auth } from "@/lib/auth";

export async function POST(req: Request) {
  const session = await auth();
  if (!session?.user || (session.user as any).role !== "ADMIN") {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    // 1. Create a dummy CertificateTemplate
    // @ts-ignore
    const template = await db.certificateTemplate.create({
      data: {
        name: "Șablon Diploma Absolvire RIMA",
        description: "Șablonul standard pentru absolvirea cursurilor RIMA Academy.",
        isDefault: true,
      }
    });

    // 2. Fetch an existing course and user to link the certificate (or use the admin)
    const course = await db.course.findFirst();
    const user = await db.user.findFirst({ where: { role: "STUDENT" } }) || await db.user.findFirst();

    if (!course || !user) {
      return NextResponse.json({ error: "Nu există cursuri sau utilizatori pentru a genera certificatul." }, { status: 400 });
    }

    // 3. Create a mock Certificate
    const certificateId = `RIMA-${new Date().getFullYear()}-${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}`;
    
    // @ts-ignore
    await db.certificate.create({
      data: {
        certificateId,
        status: "ISSUED",
        issueDate: new Date(),
        userId: user.id,
        courseId: course.id,
        templateId: template.id
      }
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Generate error:", error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
