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

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

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

    if (!body.options || !Array.isArray(body.options) || body.options.length !== 4) {
      return NextResponse.json(
        { error: 'باید دقیقاً ۴ گزینه وارد شود' },
        { status: 400 }
      );
    }

    if (body.options.some((opt: string) => !opt || !opt.trim())) {
      return NextResponse.json(
        { error: 'تمام گزینه‌ها باید پر شوند' },
        { status: 400 }
      );
    }

    if (!body.correctAnswer || !['A', 'B', 'C', 'D'].includes(body.correctAnswer)) {
      return NextResponse.json(
        { error: 'گزینه صحیح نامعتبر است' },
        { status: 400 }
      );
    }

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

    const maxOrderQuestion = await prisma.question.findFirst({
      where: { examId: body.examId },
      orderBy: { order: 'desc' },
    });

    const order = (maxOrderQuestion?.order ?? -1) + 1;

    const question = await prisma.question.create({
      data: {
        text: body.text.trim(),
        options: JSON.stringify(body.options),
        correctAnswer: body.correctAnswer,
        order,
        examId: body.examId,
      },
    });

    return NextResponse.json({ question }, { status: 201 });
  } catch (error) {
    console.error('Error creating question:', error);
    return NextResponse.json(
      { error: 'خطا در ایجاد سوال' },
      { status: 500 }
    );
  }
}
