import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, getAllPermissions } from "@/lib/adminAuth";
import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

export async function OPTIONS(request: NextRequest) {
  return corsPreflight(request);
}

// Beim App-Start abgefragt: noch gültige Session? Dann direkt zum Dashboard
// statt zum Login. Liefert auch die Permissions mit, damit der Renderer von
// Anfang an weiß, welche Bereiche/Kacheln für diese Rolle sichtbar sein
// dürfen (siehe getAllPermissions/adminAuth.ts — dieselbe Quelle wie die
// Webseite, keine eigene Rechte-Logik in der App).
export async function GET(request: NextRequest) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ loggedIn: false }, { headers });
  }
  await connectDB();
  const client = await Client.findById(clientId).select("name").lean();
  const permissions = await getAllPermissions();
  return NextResponse.json({ loggedIn: true, name: client?.name || "", permissions }, { headers });
}
