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

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

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 body = await request.json().catch(() => null);
  const text = typeof body?.text === "string" ? body.text : "";
  if (!text.trim()) return NextResponse.json({ error: "Bitte einen Text eingeben." }, { status: 400, headers });
  await addTodoSubtaskAction(todoId, text);
  return NextResponse.json({ ok: true }, { headers });
}
