import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { createCalendarEventAction } from "@/lib/actions/calendars";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

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

export async function POST(request: NextRequest) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const body = await request.json().catch(() => null);
  const formData = new FormData();
  formData.set("calendarId", typeof body?.calendarId === "string" ? body.calendarId : "");
  formData.set("title", typeof body?.title === "string" ? body.title : "");
  formData.set("start", typeof body?.start === "string" ? body.start : "");
  formData.set("end", typeof body?.end === "string" ? body.end : "");
  formData.set("description", typeof body?.description === "string" ? body.description : "");
  if (body?.allDay) formData.set("allDay", "on");

  const result = await createCalendarEventAction({}, formData);
  if (result.error) return NextResponse.json({ error: result.error }, { status: 400, headers });
  return NextResponse.json({ ok: true }, { headers });
}
