import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { updateTodoStatusAction } from "@/lib/actions/todos";
import { TODO_STATUSES } from "@/models/Todo";
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 status = TODO_STATUSES.includes(body?.status) ? body.status : null;
  if (!status) return NextResponse.json({ error: "Ungültiger Status." }, { status: 400, headers });

  await updateTodoStatusAction(todoId, status);
  return NextResponse.json({ ok: true }, { headers });
}
