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

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

  if (result instanceof NextResponse) {
    return result;
  }

  const { user } = result;
  const { phone } = params;

  const appointments = await prisma.appointment.findMany({
    where: {
      patientPhone: phone,
      date: {
        gte: new Date(),
      },
    },
    include: {
      patient: {
        select: {
          name: true,
          phone: true,
        },
      },
      payment: {
        select: {
          id: true,
          amount: true,
          status: true,
        },
      },
    },
    orderBy: {
      date: "desc",
    },
  });

  return NextResponse.json({
    success: true,
    appointments: appointments.map((apt) => ({
      id: apt.id,
      patientName: apt.patient?.name,
      patientPhone: apt.patientPhone,
      date: apt.date,
      status: apt.status,
      isCrisis: apt.isCrisis,
      payment: apt.payment
        ? {
            id: apt.payment.id,
            amount: apt.payment.amount,
            status: apt.payment.status,
          }
        : null,
      createdAt: apt.createdAt,
      updatedAt: apt.updatedAt,
    })),
  });
}
