import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/infrastructure/db/prisma";
import { withAuth, ROLES } from "@/middleware/auth";

export async function GET(request: NextRequest) {
  const result = await withAuth(request, [ROLES.ASSISTANT, ROLES.THERAPIST]);

  if (result instanceof NextResponse) {
    return result;
  }

  const { user } = result;

  const payments = await prisma.payment.findMany({
    where: {
      status: "PENDING",
    },
    include: {
      appointment: {
        include: {
          patient: {
            select: {
              name: true,
              phone: true,
            },
          },
        },
      },
    },
    orderBy: {
      createdAt: "asc",
    },
  });

  return NextResponse.json({
    success: true,
    payments: payments.map((payment) => ({
      id: payment.id,
      appointmentId: payment.appointmentId,
      amount: payment.amount,
      status: payment.status,
      proofUrl: payment.proofUrl,
      rejectedReason: payment.rejectedReason,
      createdAt: payment.createdAt,
      patientName: payment.appointment?.patient?.name,
      patientPhone: payment.appointment?.patient?.phone,
    })),
  });
}
