import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getSession, SESSION_COOKIE } from "@/lib/auth";
import { MENU_AUDIENCES, emptyHidden, type MenuAudience } from "@/lib/menu-access";

export async function GET() {
  const session = await getSession();

  // No session at all
  if (!session) {
    return NextResponse.json({ user: null }, { status: 401 });
  }

  const user = await prisma.user.findUnique({
    where: { id: session.userId },
    select: {
      id: true,
      name: true,
      email: true,
      username: true,
      role: true,
      staffId: true,
      institution: {
        select: {
          id: true, name: true, type: true, status: true, email: true, logo: true,
          academicLabels: true, enabledModules: true,
        },
      },
    },
  });

  // Session references a user that no longer exists (e.g. database re-seeded):
  // clear the stale cookie so the client can fall back to the login page.
  if (!user) {
    const res = NextResponse.json({ user: null }, { status: 401 });
    res.cookies.set(SESSION_COOKIE, "", { httpOnly: true, maxAge: 0, path: "/" });
    return res;
  }

  // Staff logins with a Student Identity maintainer assignment get a link to
  // /portal/identity in their member area.
  let isIdentityManager = false;
  if ((user.role === "TEACHER" || user.role === "STAFF") && user.institution && user.staffId) {
    isIdentityManager = !!(await prisma.identityManager.findFirst({
      where: { institutionId: user.institution.id, staffId: user.staffId },
      select: { id: true },
    }));
  }

  // Subscription menu access: hidden sidebar menus per audience for this
  // institution (no rows = everything visible). The portal and member
  // layouts consume this to filter their sidebars.
  const menuAccessHidden = emptyHidden();
  if (user.institution) {
    const menuRows = await prisma.menuAccess.findMany({
      where: { institutionId: user.institution.id, visible: false },
      select: { audience: true, menuKey: true },
    });
    for (const row of menuRows) {
      if ((MENU_AUDIENCES as readonly string[]).includes(row.audience)) {
        menuAccessHidden[row.audience as MenuAudience].push(row.menuKey);
      }
    }
  }

  return NextResponse.json({ user: { ...user, isIdentityManager }, menuAccess: { hidden: menuAccessHidden } });
}
