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

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

export async function PATCH(request: NextRequest) {
  const headers = corsHeaders(request);
  const viewerId = await getSessionClientId();
  if (!viewerId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const body = await request.json().catch(() => null);
  const ids = Array.isArray(body?.ids) ? body.ids.filter((id: unknown): id is string => typeof id === "string") : [];
  if (!ids.length) return NextResponse.json({ error: "Keine ToDos ausgewählt." }, { status: 400, headers });

  await bulkUpdateTodosAction(ids, {
    status: typeof body?.status === "string" ? body.status : undefined,
    assigneeId: typeof body?.assigneeId === "string" ? body.assigneeId : undefined,
    dueDate: body?.dueDate === null ? null : typeof body?.dueDate === "string" ? body.dueDate : undefined,
  });
  return NextResponse.json({ ok: true }, { headers });
}

export async function DELETE(request: NextRequest) {
  const headers = corsHeaders(request);
  const viewerId = await getSessionClientId();
  if (!viewerId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const body = await request.json().catch(() => null);
  const ids = Array.isArray(body?.ids) ? body.ids.filter((id: unknown): id is string => typeof id === "string") : [];
  if (!ids.length) return NextResponse.json({ error: "Keine ToDos ausgewählt." }, { status: 400, headers });

  await bulkDeleteTodosAction(ids);
  return NextResponse.json({ ok: true }, { headers });
}
