import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { queryRaw } from "@/lib/db";
import { prisma } from "@/lib/db";
import { isTripParticipant } from "@/lib/queries";

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

  const sp = req.nextUrl.searchParams;
  const participantId = sp.get("participant_id");

  // Return payment history between current user and a participant
  const rows = await queryRaw<{
    id: number;
    from_participant_id: number;
    from_name: string;
    to_participant_id: number;
    to_name: string;
    amount: number;
    payment_date: string;
    notes: string | null;
    linked_transaction_id: number | null;
    trip_id: number | null;
    trip_name: string | null;
    created_at: string;
  }>(
    // trip_id was stored but never returned, so history could not show which tab
    // a payment settled — and a grouped transfer looks like a duplicate until you
    // can see that its rows carry different scopes.
    `SELECT sp.id, sp.from_participant_id, pf.name as from_name,
            sp.to_participant_id, pt.name as to_name,
            sp.amount, sp.payment_date, sp.notes,
            sp.linked_transaction_id, sp.trip_id, tr.name as trip_name,
            sp.created_at
     FROM split_payments sp
     JOIN participants pf ON pf.id = sp.from_participant_id
     JOIN participants pt ON pt.id = sp.to_participant_id
     LEFT JOIN trips tr ON tr.id = sp.trip_id
     WHERE (sp.from_participant_id = $1 OR sp.to_participant_id = $1)
       AND (sp.from_participant_id = $2 OR sp.to_participant_id = $2)
     ORDER BY sp.payment_date DESC, sp.created_at DESC`,
    [user.id, participantId ? Number(participantId) : user.id]
  );

  return NextResponse.json(rows);
}

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 {
    from_participant_id: number;
    to_participant_id: number;
    amount: number;
    payment_date: string;
    notes?: string;
    linked_transaction_id?: number;
    trip_id?: number | null;
  };

  const { from_participant_id, to_participant_id, amount, payment_date, notes, linked_transaction_id, trip_id } = body;

  if (!from_participant_id || !to_participant_id || !amount || !payment_date) {
    return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
  }
  if (amount <= 0) {
    return NextResponse.json({ error: "Amount must be positive" }, { status: 400 });
  }
  if (from_participant_id !== user.id && to_participant_id !== user.id) {
    return NextResponse.json({ error: "A payment must involve you" }, { status: 403 });
  }

  // Scope. `trip_id` existed in the schema from migration 0022 but this route
  // never read it, so every payment recorded in the app landed on the household
  // tab and the 9 trip-scoped rows had to be written by hand in SQL.
  //
  // "Both" needs no extra shape: one transfer becomes one row per scope, all
  // carrying the same linked_transaction_id — there is deliberately no unique
  // constraint on it. That is how tx 4121's $4,794.06 sits as $1,145.52 against
  // Europe — Sonu + Sunny and $3,648.54 against household.
  if (trip_id != null && !(await isTripParticipant(trip_id, user.id))) {
    return NextResponse.json(
      { error: "Cannot scope a payment to a trip you are not on" },
      { status: 403 }
    );
  }

  const payment = await prisma.split_payments.create({
    data: {
      from_participant_id,
      to_participant_id,
      amount,
      payment_date: new Date(payment_date),
      notes: notes || null,
      linked_transaction_id: linked_transaction_id || null,
      trip_id: trip_id ?? null,
    },
  });

  return NextResponse.json(payment);
}

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

  const sp = req.nextUrl.searchParams;
  const id = Number(sp.get("id"));
  if (!id) return NextResponse.json({ error: "id required" }, { status: 400 });

  // This deleted by id with no check at all: any authenticated participant could
  // erase any settlement, which silently resurrects a discharged debt — the same
  // class of damage as the split rewrite that reset `settled`. Deleting a payment
  // must be limited to the two people it is between.
  const existing = await prisma.split_payments.findUnique({ where: { id } });
  if (!existing) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (existing.from_participant_id !== user.id && existing.to_participant_id !== user.id) {
    return NextResponse.json({ error: "Not your payment to delete" }, { status: 403 });
  }

  await prisma.split_payments.delete({ where: { id } });
  return NextResponse.json({ ok: true });
}
