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

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

    const questions = await db.mcqQuestion.findMany({
      orderBy: { createdAt: 'desc' },
    });

    return NextResponse.json({ success: true, questions });
  } catch (error) {
    console.error('Admin MCQ fetch error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch questions' },
      { status: 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
    const identifier = `admin-mcq-post:${getRateLimitIdentifier(request)}`;
    const rateLimit = checkRateLimit(identifier, RATE_LIMITS.adminWrite);
    if (!rateLimit.allowed) return rateLimitError(rateLimit.resetTime);

    const { question, optionA, optionB, optionC, optionD, correctAnswer, category, difficulty, explanation, class: mcqClass, topic } =
      await request.json();

    if (!question || !optionA || !optionB || !optionC || !optionD || !correctAnswer) {
      return NextResponse.json(
        { success: false, error: 'All question fields are required' },
        { status: 400 }
      );
    }

    // Validate answer
    if (!isValidMcqAnswer(correctAnswer)) {
      return NextResponse.json(
        { success: false, error: 'Correct answer must be A, B, C, or D' },
        { status: 400 }
      );
    }

    // Validate question length
    if (!isValidLength(question, 1, 1000)) {
      return NextResponse.json(
        { success: false, error: 'Question must be between 1 and 1000 characters' },
        { 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'];

    const newQuestion = await db.mcqQuestion.create({
      data: {
        question: sanitizeString(question),
        optionA: sanitizeString(optionA),
        optionB: sanitizeString(optionB),
        optionC: sanitizeString(optionC),
        optionD: sanitizeString(optionD),
        correctAnswer,
        category: validCategories.includes(category) ? category : 'gk',
        class: mcqClass && validClasses.includes(mcqClass) ? mcqClass : 'GK',
        topic: topic ? sanitizeString(topic) : 'General',
        difficulty: validDifficulties.includes(difficulty) ? difficulty : 'medium',
        explanation: explanation ? sanitizeString(explanation) : null,
      },
    });

    return NextResponse.json({ success: true, question: newQuestion });
  } catch (error) {
    console.error('Admin MCQ create error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to create question' },
      { status: 500 }
    );
  }
}

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

    const { id } = await request.json();

    if (!id) {
      return NextResponse.json(
        { success: false, error: 'Question ID is required' },
        { status: 400 }
      );
    }

    if (!isValidId(id)) {
      return NextResponse.json(
        { success: false, error: 'Invalid question ID format' },
        { status: 400 }
      );
    }

    await db.mcqQuestion.delete({ where: { id } });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Admin MCQ delete error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to delete question' },
      { status: 500 }
    );
  }
}
