import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
import { MY_SPEND_SCOPE, STATEMENTS_JOIN, EXCLUDE_RECONCILED_SOURCE, EFFECTIVE_CATEGORY, mySplitOf } from "@/lib/analytics-sql";
import { bankLabel } from "@/lib/queries";

const MY_AMOUNT = mySplitOf(`COALESCE(t.amount_aud, t.amount)`);

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ merchant: string }> }
) {
  const user = await getCurrentUser(req);
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { merchant } = await params;
  const decoded = decodeURIComponent(merchant);

  const transactions = await queryRaw<{
    id: number;
    transaction_date: string;
    description: string;
    amount: number;
    amount_aud: number | null;
    my_amount: number;
    transaction_type: string;
    category: string;
    bank_name: string;
    statement_id: number;
  }>(`
    SELECT
      t.id,
      t.transaction_date::text,
      t.description,
      t.amount,
      t.amount_aud,
      CASE
        WHEN t.transaction_type IN ('refund', 'credit') THEN -${MY_AMOUNT}
        ELSE ${MY_AMOUNT}
      END::numeric(10,2) as my_amount,
      t.transaction_type,
      ${EFFECTIVE_CATEGORY} as category,
      ${bankLabel()} as bank_name,
      t.statement_id
    FROM transactions t
    ${STATEMENTS_JOIN}
    LEFT JOIN transaction_overrides o ON o.transaction_id = t.id
    LEFT JOIN transaction_splits ts ON ts.transaction_id = t.id AND ts.participant_id = $1
    WHERE ${MY_SPEND_SCOPE()}
      AND t.transaction_type IN ('debit', 'fee', 'interest', 'refund', 'credit')
      AND COALESCE(o.merchant_normalized, t.merchant_normalized, t.merchant_name, t.description) = $2
      AND ${EXCLUDE_RECONCILED_SOURCE}
    ORDER BY t.transaction_date DESC
    LIMIT 500
  `, [user.id, decoded]);

  return NextResponse.json({ transactions });
}
