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

export async function POST(request: NextRequest) {
  try {
    // Rate limit MCQ submissions
    const identifier = `mcq-submit:${getRateLimitIdentifier(request)}`;
    const rateLimit = checkRateLimit(identifier, RATE_LIMITS.api);
    if (!rateLimit.allowed) return rateLimitError(rateLimit.resetTime);

    const body = await request.json();
    const { userId, category, topic, totalQuestions, correctAnswers, timeTaken } = body;

    if (!userId || !category || totalQuestions === undefined || correctAnswers === undefined) {
      return NextResponse.json(
        { error: 'Missing required fields: userId, category, totalQuestions, correctAnswers' },
        { status: 400 }
      );
    }

    if (!isValidId(userId)) {
      return NextResponse.json(
        { error: 'Invalid user ID format' },
        { status: 400 }
      );
    }

    // Validate numeric values
    const totalQ = parseInt(String(totalQuestions));
    const correctA = parseInt(String(correctAnswers));
    const time = timeTaken ? parseInt(String(timeTaken)) : 0;

    if (isNaN(totalQ) || totalQ < 1 || totalQ > 200) {
      return NextResponse.json(
        { error: 'totalQuestions must be between 1 and 200' },
        { status: 400 }
      );
    }

    if (isNaN(correctA) || correctA < 0 || correctA > totalQ) {
      return NextResponse.json(
        { error: 'correctAnswers must be between 0 and totalQuestions' },
        { status: 400 }
      );
    }

    if (time < 0 || time > 3600) {
      return NextResponse.json(
        { error: 'timeTaken must be between 0 and 3600 seconds' },
        { status: 400 }
      );
    }

    const validCategories = ['gk', 'ssc', 'hsc', 'class6-10', 'bangla', 'english', 'math', 'science', 'admission'];
    if (!validCategories.includes(category)) {
      return NextResponse.json(
        { error: 'Invalid category' },
        { status: 400 }
      );
    }

    const score = (correctA / totalQ) * 100;

    const result = await db.mcqResult.create({
      data: {
        userId,
        category: sanitizeString(category),
        topic: topic ? sanitizeString(String(topic)) : null,
        totalQuestions: totalQ,
        correctAnswers: correctA,
        score: parseFloat(score.toFixed(2)),
        timeTaken: time,
      },
    });

    return NextResponse.json({ result }, { status: 201 });
  } catch (error) {
    console.error('MCQ POST error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const category = searchParams.get('category');
    const topic = searchParams.get('topic');
    const difficulty = searchParams.get('difficulty');
    const classId = searchParams.get('classId');
    const subjectId = searchParams.get('subjectId');
    const topicId = searchParams.get('topicId');
    const includeAnswers = searchParams.get('includeAnswers') === 'true';
    const random = searchParams.get('random') === 'true';
    const limit = Math.min(50, Math.max(1, parseInt(searchParams.get('limit') || '10')));

    const where: Record<string, unknown> = {};

    const validCategories = ['gk', 'ssc', 'hsc', 'class6-10', 'bangla', 'english', 'math', 'science', 'admission'];
    const validDifficulties = ['easy', 'medium', 'hard'];

    if (category && validCategories.includes(category)) where.category = category;
    if (topic) where.topic = topic;
    if (difficulty && validDifficulties.includes(difficulty)) where.difficulty = difficulty;
    if (classId) where.classId = classId;
    if (subjectId) where.subjectId = subjectId;
    if (topicId) where.topicId = topicId;

    const questions = await db.mcqQuestion.findMany({
      where,
      take: limit,
      orderBy: random ? undefined : { createdAt: 'desc' },
    });

    if (includeAnswers) {
      // Return full question data including correctAnswer for quiz mode
      const fullQuestions = questions.map(({ correctAnswer, ...rest }) => ({
        ...rest,
        correctAnswer,
      }));

      return NextResponse.json({ questions: fullQuestions });
    }

    // Don't send correct answers to the client — remove correctAnswer field
    const safeQuestions = questions.map(({ correctAnswer, ...rest }) => ({
      ...rest,
      options: {
        A: rest.optionA,
        B: rest.optionB,
        C: rest.optionC,
        D: rest.optionD,
      },
    }));

    return NextResponse.json({ questions: safeQuestions });
  } catch (error) {
    console.error('MCQ GET error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
