import { NextResponse } from "next/server";
import { db } from "@/lib/prisma";
import { UserRole } from "@prisma/client";
import { supabaseServer } from "@/lib/supabase/server";

export async function GET() {
  try {
    const supabase = await supabaseServer();
    if (!supabase) {
      return NextResponse.json({ user: null, isTeacher: false });
    }

    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ user: null, isTeacher: false });
    }

    const profile = await db.profile.findUnique({
      where: { id: user.id },
      select: { role: true },
    }).catch(() => null);

    const isTeacher =
      !!profile &&
      (profile.role === UserRole.TEACHER || profile.role === UserRole.SUPER_ADMIN);

    return NextResponse.json({
      user: { id: user.id, email: user.email ?? null },
      isTeacher,
    });
  } catch (error) {
    console.error("Failed to resolve auth session route. Returning anonymous fallback.", error);
    return NextResponse.json({ user: null, isTeacher: false });
  }
}
