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 classId = searchParams.get('classId');

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

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

    const result = subjects.map((sub) => ({
      id: sub.id,
      name: sub.name,
      nameBn: sub.nameBn,
      description: sub.description,
      icon: sub.icon,
      classId: sub.classId,
      order: sub.order,
      isActive: sub.isActive,
      createdAt: sub.createdAt,
      updatedAt: sub.updatedAt,
      mcqClass: sub.mcqClass,
      topicCount: sub._count.topics,
      questionCount: sub._count.questions,
    }));

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

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

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

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

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

    const newSubject = await db.mcqSubject.create({
      data: {
        name: sanitizeString(name),
        nameBn: nameBn ? sanitizeString(nameBn) : null,
        description: description ? sanitizeString(description) : null,
        icon: icon ? sanitizeString(icon) : null,
        classId,
        order: typeof order === 'number' ? order : 0,
      },
      include: {
        mcqClass: {
          select: { id: true, name: true, nameBn: true },
        },
      },
    });

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