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

export async function POST(req: NextRequest) {
  const user = await getCurrentUser(req);
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });

  const body = await req.json() as {
    bank_name: string;
    /**
     * Optional provenance label, stored on every row as `source`. With a
     * `source_ref` per row it makes a re-import a no-op; without it this path
     * has no idempotency at all.
     */
    source?: string;
    transactions: {
      date: string;
      description: string;
      amount: number;
      transaction_type: string;
      merchant_name?: string;
      foreign_currency_amount?: number;
      foreign_currency_code?: string;
      category?: string;
      account?: string;
      source_ref?: string;
    }[];
  };

  if (!Array.isArray(body.transactions) || body.transactions.length === 0) {
    return NextResponse.json({ error: "No transactions provided" }, { status: 400 });
  }

  const tagId = await ensureTag("csv-import", "#8b5cf6");
  const inserted = await batchInsertCSVTransactions(user.id, body.transactions, tagId, body.source);

  return NextResponse.json({ inserted }, { status: 201 });
}
