import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '../../../lib/prisma';
import { generateSlug } from '../../../lib/utils';

export async function GET() {
  try {
    const exams = await prisma.exam.findMany({
      include: {
        questions: {
          orderBy: { order: 'asc' },
        },
      },
      orderBy: { createdAt: 'desc' },
    });

    return NextResponse.json({ exams });
  } catch (error) {
    console.error('Error fetching exams:', error);
    return NextResponse.json(
      { error: 'خطا در دریافت آزمون‌ها' },
      { status: 500 }
    );
  }
}

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

    if (!body.title || !body.title.trim()) {
      return NextResponse.json(
        { error: 'عنوان آزمون الزامی است' },
        { status: 400 }
      );
    }

    const slug = generateSlug();

    const exam = await prisma.exam.create({
      data: {
        title: body.title.trim(),
        description: body.description?.trim() || '',
        slug,
      },
      include: {
        questions: true,
      },
    });

    return NextResponse.json({ exam }, { status: 201 });
  } catch (error) {
    console.error('Error creating exam:', error);
    return NextResponse.json(
      { error: 'خطا در ایجاد آزمون' },
      { status: 500 }
    );
  }
}
