import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; import { db } from '@/lib/db'; import { sections, classes, periods, eq, and } from '@/lib/db/schema'; export async function GET() { try { const session = await getServerSession(authOptions); if (!session?.user || session.user.role !== 'admin') { return NextResponse.json( { error: 'No autorizado' }, { status: 401 } ); } const allSections = await db .select({ id: sections.id, name: sections.name, classId: sections.classId, className: classes.name, classCode: classes.code, periodId: sections.periodId, periodName: periods.name, maxStudents: sections.maxStudents, isActive: sections.isActive, createdAt: sections.createdAt, }) .from(sections) .leftJoin(classes, eq(sections.classId, classes.id)) .leftJoin(periods, eq(sections.periodId, periods.id)) .orderBy(classes.code, sections.name); return NextResponse.json(allSections); } catch (error) { console.error('Error fetching sections:', error); return NextResponse.json( { error: 'Error interno del servidor' }, { status: 500 } ); } } export async function POST(request: NextRequest) { try { const session = await getServerSession(authOptions); if (!session?.user || session.user.role !== 'admin') { return NextResponse.json( { error: 'No autorizado' }, { status: 401 } ); } const { name, classId, periodId, maxStudents } = await request.json(); // Validaciones if (!name || !classId || !periodId || !maxStudents) { return NextResponse.json( { error: 'Todos los campos son requeridos' }, { status: 400 } ); } if (typeof maxStudents !== 'number' || maxStudents < 1) { return NextResponse.json( { error: 'El número máximo de estudiantes debe ser mayor a 0' }, { status: 400 } ); } // Verificar si la clase existe const existingClass = await db .select() .from(classes) .where(eq(classes.id, classId)) .limit(1); if (existingClass.length === 0) { return NextResponse.json( { error: 'La clase seleccionada no existe' }, { status: 400 } ); } // Verificar si el período existe const existingPeriod = await db .select() .from(periods) .where(eq(periods.id, periodId)) .limit(1); if (existingPeriod.length === 0) { return NextResponse.json( { error: 'El período seleccionado no existe' }, { status: 400 } ); } // Verificar si ya existe una sección con el mismo nombre para la misma clase y período const existingSection = await db .select() .from(sections) .where(and( eq(sections.name, name), eq(sections.classId, classId), eq(sections.periodId, periodId) )) .limit(1); if (existingSection.length > 0) { return NextResponse.json( { error: 'Ya existe una sección con este nombre para la misma clase y período' }, { status: 400 } ); } // Crear sección const [newSection] = await db .insert(sections) .values({ name, classId, periodId, maxStudents, isActive: true, }) .returning({ id: sections.id, name: sections.name, classId: sections.classId, periodId: sections.periodId, maxStudents: sections.maxStudents, isActive: sections.isActive, createdAt: sections.createdAt, }); return NextResponse.json(newSection, { status: 201 }); } catch (error) { console.error('Error creating section:', error); return NextResponse.json( { error: 'Error interno del servidor' }, { status: 500 } ); } }