import { NextResponse } from "next/server"
import { eq } from "drizzle-orm"

import { auth } from "@/auth"
import { db } from "@/shared/db"
import { roles, users, usersToRoles } from "@/shared/db/schema"

export const dynamic = "force-dynamic"

export async function GET() {
  const session = await auth()
  const userId = String(session?.user?.id ?? "").trim()
  if (!userId) {
    return NextResponse.json({ required: false })
  }

  const [row, roleRows] = await Promise.all([
    db.query.users.findFirst({
      where: eq(users.id, userId),
      columns: { onboardedAt: true },
    }),
    db
      .select({ name: roles.name })
      .from(usersToRoles)
      .innerJoin(roles, eq(usersToRoles.roleId, roles.id))
      .where(eq(usersToRoles.userId, userId)),
  ])

  const normalizeRole = (value: string) => {
    const role = value.trim().toLowerCase()
    if (role === "grade_head" || role === "teaching_head") return "teacher"
    if (role === "admin" || role === "student" || role === "teacher" || role === "parent") return role
    return ""
  }

  const mappedRoles = roleRows.map((r) => normalizeRole(r.name)).filter(Boolean)
  const resolvedRole = mappedRoles.find((r) => r === "admin")
    ?? mappedRoles.find((r) => r === "teacher")
    ?? mappedRoles.find((r) => r === "parent")
    ?? mappedRoles.find((r) => r === "student")
    ?? "student"

  const required = !row?.onboardedAt
  return NextResponse.json({ required, role: resolvedRole })
}
