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

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

    const classes = await db.mcqClass.findMany({
      orderBy: { order: 'asc' },
      include: {
        _count: {
          select: {
            subjects: true,
            questions: true,
          },
        },
      },
    });

    const result = classes.map((cls) => ({
      id: cls.id,
      name: cls.name,
      nameBn: cls.nameBn,
      description: cls.description,
      order: cls.order,
      isActive: cls.isActive,
      createdAt: cls.createdAt,
      updatedAt: cls.updatedAt,
      subjectCount: cls._count.subjects,
      questionCount: cls._count.questions,
    }));

    return NextResponse.json({ success: true, classes: result });
  } catch (error) {
    console.error('Admin MCQ classes fetch error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch classes' },
      { 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, order } = body;

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

    // Check for duplicate name
    const existing = await db.mcqClass.findUnique({ where: { name } });
    if (existing) {
      return NextResponse.json(
        { success: false, error: 'A class with this name already exists' },
        { status: 409 }
      );
    }

    const newClass = await db.mcqClass.create({
      data: {
        name: sanitizeString(name),
        nameBn: nameBn ? sanitizeString(nameBn) : null,
        description: description ? sanitizeString(description) : null,
        order: typeof order === 'number' ? order : 0,
      },
    });

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