import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyAdminPermission } from '@/lib/auth';
import { sanitizeString, isValidLength, isValidMcqAnswer } from '@/lib/validation';
import { checkRateLimit, getRateLimitIdentifier, rateLimitError, RATE_LIMITS } from '@/lib/rate-limit';

const MAX_BULK_QUESTIONS = 500;

export async function POST(request: NextRequest) {
  try {
    // Auth check
    const authResult = await verifyAdminPermission(request, 'canManageMCQ');
    if ('error' in authResult) return authResult.error;

    // Rate limit - stricter for bulk operations
    const identifier = `admin-mcq-bulk:${getRateLimitIdentifier(request)}`;
    const rateLimit = checkRateLimit(identifier, { maxRequests: 5, windowMs: 60 * 1000 });
    if (!rateLimit.allowed) return rateLimitError(rateLimit.resetTime);

    const body = await request.json();
    const { questions, classId, subjectId, topicId } = body;

    if (!Array.isArray(questions) || questions.length === 0) {
      return NextResponse.json(
        { success: false, error: 'questions array is required and must not be empty' },
        { status: 400 }
      );
    }

    if (questions.length > MAX_BULK_QUESTIONS) {
      return NextResponse.json(
        { success: false, error: `Maximum ${MAX_BULK_QUESTIONS} questions per bulk request` },
        { status: 400 }
      );
    }

    // Validate optional parent IDs if provided at bulk level
    if (classId) {
      const cls = await db.mcqClass.findUnique({ where: { id: classId } });
      if (!cls) {
        return NextResponse.json(
          { success: false, error: 'Referenced class does not exist' },
          { status: 400 }
        );
      }
    }

    if (subjectId) {
      const sub = await db.mcqSubject.findUnique({ where: { id: subjectId } });
      if (!sub) {
        return NextResponse.json(
          { success: false, error: 'Referenced subject does not exist' },
          { status: 400 }
        );
      }
    }

    if (topicId) {
      const tpc = await db.mcqTopic.findUnique({ where: { id: topicId } });
      if (!tpc) {
        return NextResponse.json(
          { success: false, error: 'Referenced topic does not exist' },
          { status: 400 }
        );
      }
    }

    const validCategories = ['gk', 'ssc', 'hsc', 'class6-8', 'class9-10', 'admission', 'bcs', 'bangla', 'english', 'math', 'science'];
    const validDifficulties = ['easy', 'medium', 'hard'];
    const validClasses = ['SSC', 'HSC', 'Admission', 'GK', 'BCS', 'Class 6-8', 'Class 9-10'];

    // Validate and prepare data
    const validQuestions: Array<Record<string, unknown>> = [];
    const errors: Array<{ index: number; error: string }> = [];

    for (let i = 0; i < questions.length; i++) {
      const q = questions[i];

      if (!q.question || !q.optionA || !q.optionB || !q.optionC || !q.optionD || !q.correctAnswer) {
        errors.push({ index: i, error: 'Missing required fields (question, optionA-D, correctAnswer)' });
        continue;
      }

      if (!isValidMcqAnswer(q.correctAnswer)) {
        errors.push({ index: i, error: 'Correct answer must be A, B, C, or D' });
        continue;
      }

      if (!isValidLength(q.question, 1, 1000)) {
        errors.push({ index: i, error: 'Question must be between 1 and 1000 characters' });
        continue;
      }

      // Bulk-level classId/subjectId/topicId serve as defaults; individual items can override
      const itemClassId = q.classId || classId || null;
      const itemSubjectId = q.subjectId || subjectId || null;
      const itemTopicId = q.topicId || topicId || null;

      validQuestions.push({
        question: sanitizeString(q.question),
        questionImage: q.questionImage ? sanitizeString(q.questionImage) : null,
        optionA: sanitizeString(q.optionA),
        optionAImage: q.optionAImage ? sanitizeString(q.optionAImage) : null,
        optionB: sanitizeString(q.optionB),
        optionBImage: q.optionBImage ? sanitizeString(q.optionBImage) : null,
        optionC: sanitizeString(q.optionC),
        optionCImage: q.optionCImage ? sanitizeString(q.optionCImage) : null,
        optionD: sanitizeString(q.optionD),
        optionDImage: q.optionDImage ? sanitizeString(q.optionDImage) : null,
        correctAnswer: q.correctAnswer,
        category: validCategories.includes(q.category) ? q.category : 'gk',
        class: q.class && validClasses.includes(q.class) ? q.class : 'GK',
        classId: itemClassId,
        subjectId: itemSubjectId,
        topicId: itemTopicId,
        topic: q.topic ? sanitizeString(q.topic) : 'General',
        difficulty: validDifficulties.includes(q.difficulty) ? q.difficulty : 'medium',
        explanation: q.explanation ? sanitizeString(q.explanation) : null,
        explanationImage: q.explanationImage ? sanitizeString(q.explanationImage) : null,
        year: q.year ? sanitizeString(String(q.year)) : null,
        source: q.source ? sanitizeString(q.source) : null,
      });
    }

    if (validQuestions.length === 0) {
      return NextResponse.json(
        {
          success: false,
          error: 'No valid questions to create',
          validationErrors: errors,
        },
        { status: 400 }
      );
    }

    // Create all valid questions using createMany for performance
    const result = await db.mcqQuestion.createMany({
      data: validQuestions,
    });

    return NextResponse.json({
      success: true,
      created: result.count,
      totalSubmitted: questions.length,
      validationErrors: errors.length > 0 ? errors : undefined,
    }, { status: 201 });
  } catch (error) {
    console.error('Admin MCQ bulk create error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to create questions in bulk' },
      { status: 500 }
    );
  }
}
