import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyAdminPermission } from '@/lib/auth';
import { sanitizeString, isValidLength, isValidId } from '@/lib/validation';

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

    const { searchParams } = new URL(request.url);
    const subjectId = searchParams.get('subjectId');

    const where: Record<string, unknown> = {};
    if (subjectId) {
      if (!isValidId(subjectId)) {
        return NextResponse.json(
          { success: false, error: 'Invalid subjectId format' },
          { status: 400 }
        );
      }
      where.subjectId = subjectId;
    }

    const topics = await db.mcqTopic.findMany({
      where,
      orderBy: [{ order: 'asc' }, { name: 'asc' }],
      include: {
        subject: {
          select: { id: true, name: true, nameBn: true, classId: true },
        },
        _count: {
          select: {
            questions: true,
          },
        },
      },
    });

    const result = topics.map((topic) => ({
      id: topic.id,
      name: topic.name,
      nameBn: topic.nameBn,
      description: topic.description,
      subjectId: topic.subjectId,
      order: topic.order,
      isActive: topic.isActive,
      createdAt: topic.createdAt,
      updatedAt: topic.updatedAt,
      subject: topic.subject,
      questionCount: topic._count.questions,
    }));

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

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

    const body = await request.json();
    const { name, nameBn, description, subjectId, order } = body;

    if (!name || !isValidLength(name, 1, 100)) {
      return NextResponse.json(
        { success: false, error: 'Topic name is required (1-100 characters)' },
        { status: 400 }
      );
    }

    if (!subjectId || !isValidId(subjectId)) {
      return NextResponse.json(
        { success: false, error: 'Valid subjectId is required' },
        { status: 400 }
      );
    }

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

    // Check for unique name within subject
    const existing = await db.mcqTopic.findUnique({
      where: { name_subjectId: { name, subjectId } },
    });
    if (existing) {
      return NextResponse.json(
        { success: false, error: 'A topic with this name already exists in this subject' },
        { status: 409 }
      );
    }

    const newTopic = await db.mcqTopic.create({
      data: {
        name: sanitizeString(name),
        nameBn: nameBn ? sanitizeString(nameBn) : null,
        description: description ? sanitizeString(description) : null,
        subjectId,
        order: typeof order === 'number' ? order : 0,
      },
      include: {
        subject: {
          select: { id: true, name: true, nameBn: true, classId: true },
        },
      },
    });

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