import { NextRequest, NextResponse } from "next/server";
import { queryRaw } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { canAccessTransactions } 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: "Unauthorized" }, { status: 403 });
  const { id } = await params;
  if (!(await canAccessTransactions(user.id, [Number(id)]))) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
  const { tag_id } = await req.json();
  if (!tag_id) return NextResponse.json({ error: "tag_id required" }, { status: 400 });
  await queryRaw(
    `INSERT INTO transaction_tags (transaction_id, tag_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
    [Number(id), Number(tag_id)]
  );
  return NextResponse.json({ ok: true });
}

export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const user = await getCurrentUser(req);
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
  const { id } = await params;
  if (!(await canAccessTransactions(user.id, [Number(id)]))) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
  const { tag_id } = await req.json();
  if (!tag_id) return NextResponse.json({ error: "tag_id required" }, { status: 400 });
  await queryRaw(
    `DELETE FROM transaction_tags WHERE transaction_id = $1 AND tag_id = $2`,
    [Number(id), Number(tag_id)]
  );
  return NextResponse.json({ ok: true });
}
