// app/api/auth/check-student.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { prisma } from '@/lib/prisma';
import { normalizeEmail } from '@/lib/normalize-email';

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const email = body?.email;
    const normalizedEmail = normalizeEmail(email);

    if (!normalizedEmail) {
      return NextResponse.json({ error: 'Email required' }, { status: 400 });
    }

    const allowedStudent = await prisma.allowedStudent.findFirst({
      where: {
        email: {
          equals: normalizedEmail,
          mode: 'insensitive',
        },
      },
    });

    if (!allowedStudent || !allowedStudent.active) {
      return NextResponse.json(
        { 
          allowed: false, 
          message: 'Email not registered for access' 
        },
        { status: 200 }
      );
    }

    // Parse course levels
    const levels = allowedStudent.levels
      .split(',')
      .map((level) => level.trim())
      .filter((level) => level.length > 0);

    return NextResponse.json(
      {
        allowed: true,
        levels,
        studentId: allowedStudent.id,
      },
      { status: 200 }
    );
  } catch (err) {
    console.error('POST /api/auth/check-student error', err);
    return NextResponse.json(
      { error: 'Failed to check student status' },
      { status: 500 }
    );
  }
}
