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

export async function POST(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 tagId = Number(id);
  const { start_date, end_date } = await req.json().catch(() => ({}));

  // Fetch the tag
  const tags = await queryRaw<{ id: number; name: string; color: string }>(
    `SELECT id, name, color FROM tags WHERE id = $1`,
    [tagId]
  );
  if (!tags[0]) return NextResponse.json({ error: "Tag not found" }, { status: 404 });
  const tag = tags[0];

  // Create trip from tag metadata
  const trip = await createTrip(user.id, {
    name: tag.name,
    color: tag.color,
    start_date: start_date ?? null,
    end_date: end_date ?? null,
  });

  // Assign all transactions with this tag to the new trip
  // The creator owns the new trip, so they participate in it by definition and
  // the assignment's participation gate passes. `assigned` is what actually
  // moved: rows the creator cannot see are skipped, so a tag spanning someone
  // else's transactions converts to a trip holding only the creator's.
  const transactionIds = await getTagTransactionIds(tagId);
  const assigned = transactionIds.length > 0
    ? await assignTransactionsToTrip(trip.id, transactionIds, user.id)
    : 0;

  return NextResponse.json({ trip, assigned, tagged: transactionIds.length }, { status: 201 });
}
