import { NextResponse } from "next/server";
import { votePoll } from "@/lib/data";

interface RouteParams {
  params: Promise<{ id: string }>;
}

interface VoteBody {
  optionIndex: number;
}

// POST /api/polls/[id]/vote — stem uitbrengen
export async function POST(
  request: Request,
  { params }: RouteParams
): Promise<NextResponse> {
  const { id } = await params;
  const body: VoteBody = await request.json();

  if (typeof body.optionIndex !== "number") {
    return NextResponse.json(
      { error: "optionIndex is verplicht" },
      { status: 400 }
    );
  }

  const updatedPoll = votePoll(id, body.optionIndex);

  if (!updatedPoll) {
    return NextResponse.json(
      { error: "Poll niet gevonden of ongeldige optie" },
      { status: 404 }
    );
  }

  return NextResponse.json(updatedPoll);
}
