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

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

// Multipart-FormData wird unverändert an die Server-Action durchgereicht
// (Muster wie bei Portfolio/Testimonials/Blog) — "files" kann mehrfach
// vorkommen (formData.getAll("files") in der Action).
export async function POST(request: NextRequest, { params }: { params: Promise<{ todoId: string }> }) {
  const headers = corsHeaders(request);
  const viewerId = await getSessionClientId();
  if (!viewerId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { todoId } = await params;
  const formData = await request.formData();
  const result = await addTodoAttachmentsAction(todoId, {}, formData);
  if (result?.error) return NextResponse.json({ error: result.error }, { status: 400, headers });
  return NextResponse.json({ ok: true }, { headers });
}
