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

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

// Nur Liste + Status — vollständiges Anlegen/Bearbeiten (Preisstufen) bleibt
// der Web-Ansicht vorbehalten, das Formular dafür ist deutlich umfangreicher
// als eine einfache Liste native rechtfertigt.
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 });
  }
  if (!(await hasPermission("services_view"))) {
    return NextResponse.json({ error: "Keine Berechtigung." }, { status: 403, headers });
  }
  const services = await getServiceList();
  return NextResponse.json({ services }, { headers });
}
