import { NextResponse } from "next/server";
import { query } from "@/lib/db/postgres";
import { parseTransactionPatch } from "@/lib/finance/api-validation";
import { TRANSACTION_COLUMNS, UUID_RE, badRequest, financeAuth, readJson, serverError, setClause, unauthorized } from "@/lib/finance/api-server";

// Kein DELETE über die Schnittstelle (Entscheidung Maro, 2026-10-12): Löschen nur in der App.

export async function GET(req: Request, context: { params: Promise<{ id: string }> }) {
  const userId = await financeAuth(req, "read");
  if (!userId) return unauthorized();
  const { id } = await context.params;
  if (!UUID_RE.test(id)) return NextResponse.json({ error: "Transaction not found" }, { status: 404 });

  try {
    const { rows } = await query(
      `SELECT ${TRANSACTION_COLUMNS} FROM finance_transactions WHERE id = $1 AND user_id = $2`,
      [id, userId]
    );
    if (!rows[0]) return NextResponse.json({ error: "Transaction not found" }, { status: 404 });
    return NextResponse.json({ transaction: rows[0] });
  } catch (error) {
    return serverError("Finance transaction GET error", error);
  }
}

export async function PATCH(req: Request, context: { params: Promise<{ id: string }> }) {
  const userId = await financeAuth(req, "write");
  if (!userId) return unauthorized();
  const { id } = await context.params;
  if (!UUID_RE.test(id)) return NextResponse.json({ error: "Transaction not found" }, { status: 404 });

  const parsed = parseTransactionPatch(await readJson(req));
  if (!parsed.ok) return badRequest(parsed.error);
  const set = setClause(parsed.value, 3);

  try {
    const { rows } = await query(
      `UPDATE finance_transactions SET ${set.text} WHERE id = $1 AND user_id = $2 RETURNING ${TRANSACTION_COLUMNS}`,
      [id, userId, ...(set.values as (string | number)[])]
    );
    if (!rows[0]) return NextResponse.json({ error: "Transaction not found" }, { status: 404 });
    return NextResponse.json({ transaction: rows[0] });
  } catch (error) {
    return serverError("Finance transaction PATCH error", error);
  }
}
