import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { assignTransactionsToTrip } from "@/lib/queries";

export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const user = await getCurrentUser(req);
  if (!user) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  const { id } = await params;
  const { transactionIds } = await req.json() as { transactionIds: number[] };
  if (!Array.isArray(transactionIds) || !transactionIds.length) {
    return NextResponse.json({ error: "transactionIds must be a non-empty array" }, { status: 400 });
  }
  try {
    const assigned = await assignTransactionsToTrip(Number(id), transactionIds, user.id);
    return NextResponse.json({ ok: true, assigned, requested: transactionIds.length });
  } catch (e) {
    return NextResponse.json(
      { error: e instanceof Error ? e.message : "Failed to assign" },
      { status: 403 }
    );
  }
}
