import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { getUpcomingShoots, getVacationPeriods } from "@/lib/calendarUpcoming";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

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

export async function GET(request: NextRequest) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }

  // Dieselben Gates wie canViewCalendar() im Web-Admin (src/lib/calendars.ts):
  // Aufträge brauchen orders_view, der Urlaubskalender (ein normaler Custom-
  // Kalender mit publicVisible) braucht calendars_view — publicVisible ist
  // kein Berechtigungs-Bypass, nur eine Sichtbarkeits-Markierung.
  const [canOrders, canCalendars] = await Promise.all([hasPermission("orders_view"), hasPermission("calendars_view")]);

  const [shoots, vacation] = await Promise.all([
    canOrders ? getUpcomingShoots() : Promise.resolve([]),
    canCalendars ? getVacationPeriods() : Promise.resolve({ calendarName: null, events: [] }),
  ]);

  return NextResponse.json({ shoots, vacation }, { headers });
}
