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

const COLUMNS = "id, category, amount_cents, currency, to_char(month, 'YYYY-MM') AS month, created_at, updated_at";

// GET /api/v1/finances/budgets?month=YYYY-MM
export async function GET(req: Request) {
  const userId = await financeAuth(req, "read");
  if (!userId) return unauthorized();
  const month = new URL(req.url).searchParams.get("month");
  if (month && !isValidMonth(month)) return badRequest("month must be YYYY-MM");
  try {
    const { rows } = month
      ? await query(`SELECT ${COLUMNS} FROM finance_budgets WHERE user_id = $1 AND month = $2 ORDER BY category`, [userId, `${month}-01`])
      : await query(`SELECT ${COLUMNS} FROM finance_budgets WHERE user_id = $1 ORDER BY month DESC, category LIMIT 200`, [userId]);
    return NextResponse.json({ budgets: rows });
  } catch (error) {
    return serverError("Finance budgets GET error", error);
  }
}

// PUT: Budget für Kategorie + Monat setzen (anlegen oder überschreiben)
export async function PUT(req: Request) {
  const userId = await financeAuth(req, "write");
  if (!userId) return unauthorized();
  const parsed = parseBudgetUpsert(await readJson(req));
  if (!parsed.ok) return badRequest(parsed.error);
  const b = parsed.value;
  try {
    const { rows } = await query(
      `INSERT INTO finance_budgets (user_id, category, amount_cents, currency, month)
       VALUES ($1, $2, $3, $4, $5)
       ON CONFLICT (user_id, category, month) DO UPDATE SET amount_cents = EXCLUDED.amount_cents, currency = EXCLUDED.currency
       RETURNING ${COLUMNS}`,
      [userId, b.category, b.amount_cents, b.currency, b.month]
    );
    return NextResponse.json({ budget: rows[0] });
  } catch (error) {
    return serverError("Finance budgets PUT error", error);
  }
}
