import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { getSettings } from "@/lib/localDb";
import { isOidcConfigured } from "@/lib/auth/oidc";
import { verifyToken } from "@/lib/auth/jwt";

export async function GET() {
  try {
    const settings = await getSettings();
    const cookieStore = await cookies();
    const token = cookieStore.get("auth_token")?.value;

    // Try new multi-user JWT first
    const jwtPayload = await verifyToken(token);
    if (jwtPayload) {
      return NextResponse.json({
        requireLogin: settings.requireLogin !== false,
        authMode: settings.authMode || "password",
        oidcConfigured: isOidcConfigured(settings),
        oidcLoginLabel: (settings.oidcLoginLabel || "Sign in with OIDC").trim() || "Sign in with OIDC",
        hasPassword: !!settings.password,
        displayName: jwtPayload.username || "User",
        loginMethod: "Password",
        oidcName: null,
        oidcEmail: null,
        oidcLogin: false,
        userId: jwtPayload.userId,
        role: jwtPayload.role,
      });
    }

    // Fallback: try legacy OIDC session
    const { getDashboardAuthSession } = await import("@/lib/auth/dashboardSession");
    const session = await getDashboardAuthSession(token);
    const requireLogin = settings.requireLogin !== false;
    const authMode = settings.authMode || "password";
    const oidcName = String(session?.oidcName || "").trim();
    const oidcEmail = String(session?.oidcEmail || "").trim();
    const displayName = oidcName || oidcEmail || (session?.oidc ? "OIDC user" : "Password user");
    const loginMethod = session?.oidc ? "OIDC" : "Password";

    return NextResponse.json({
      requireLogin,
      authMode,
      oidcConfigured: isOidcConfigured(settings),
      oidcLoginLabel: (settings.oidcLoginLabel || "Sign in with OIDC").trim() || "Sign in with OIDC",
      hasPassword: !!settings.password,
      displayName,
      loginMethod,
      oidcName: oidcName || null,
      oidcEmail: oidcEmail || null,
      oidcLogin: !!session?.oidc,
    });
  } catch {
    return NextResponse.json({
      requireLogin: true,
      authMode: "password",
      oidcConfigured: false,
      oidcLoginLabel: "Sign in with OIDC",
      hasPassword: false,
      displayName: "Password user",
      loginMethod: "Password",
      oidcName: null,
      oidcEmail: null,
      oidcLogin: false,
    });
  }
}
