import { NextRequest, NextResponse } from "next/server";
import { db } from "@/db";
import { verifySession } from "@/lib/auth";
import {
  patients,
  problems,
  medications,
  labResults,
  orders,
  careGoals,
  vitals,
  clinicalNotes,
  providers,
} from "@/db/schema";
import { eq, desc } from "drizzle-orm";

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await verifySession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const patientId = parseInt(id, 10);
  if (isNaN(patientId)) {
    return NextResponse.json({ error: "Invalid patient ID" }, { status: 400 });
  }

  const [patient] = await db
    .select()
    .from(patients)
    .where(eq(patients.id, patientId))
    .limit(1);

  if (!patient) {
    return NextResponse.json({ error: "Patient not found" }, { status: 404 });
  }

  // Get PCP info
  let pcp = null;
  if (patient.pcpId) {
    const [pcpData] = await db
      .select({ firstName: providers.firstName, lastName: providers.lastName })
      .from(providers)
      .where(eq(providers.id, patient.pcpId))
      .limit(1);
    pcp = pcpData ?? null;
  }

  const patientProblems = await db
    .select()
    .from(problems)
    .where(eq(problems.patientId, patientId));

  const patientMeds = await db
    .select()
    .from(medications)
    .where(eq(medications.patientId, patientId));

  const patientLabs = await db
    .select()
    .from(labResults)
    .where(eq(labResults.patientId, patientId))
    .orderBy(desc(labResults.resultDate));

  const patientOrders = await db
    .select()
    .from(orders)
    .where(eq(orders.patientId, patientId))
    .orderBy(desc(orders.orderedAt));

  const patientGoals = await db
    .select()
    .from(careGoals)
    .where(eq(careGoals.patientId, patientId));

  const patientVitals = await db
    .select()
    .from(vitals)
    .where(eq(vitals.patientId, patientId))
    .orderBy(desc(vitals.recordedAt));

  const patientNotes = await db
    .select()
    .from(clinicalNotes)
    .where(eq(clinicalNotes.patientId, patientId))
    .orderBy(desc(clinicalNotes.visitDate));

  return NextResponse.json({
    patient: { ...patient, pcp },
    problems: patientProblems,
    medications: patientMeds,
    labs: patientLabs,
    orders: patientOrders,
    goals: patientGoals,
    vitals: patientVitals,
    notes: patientNotes,
  });
}
