import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { createClient } from '@/lib/auth/server';
import { getPatient } from '@/app/epd/patients/actions';
import { getIntakesByPatientId } from '@/app/epd/patients/[id]/intakes/actions';
import { getPatientEncounters } from '@/app/epd/agenda/actions';

interface RouteParams {
  params: Promise<{ patientId: string }>;
}

export async function GET(_request: NextRequest, { params }: RouteParams) {
  try {
    const { patientId } = await params;

    if (!z.string().uuid().safeParse(patientId).success) {
      return NextResponse.json(
        { error: 'patientId moet een geldige UUID zijn' },
        { status: 400 }
      );
    }

    const supabase = await createClient();
    const { data: authData } = await supabase.auth.getUser();
    if (!authData?.user) {
      return NextResponse.json({ error: 'Niet geautoriseerd' }, { status: 401 });
    }

    const patient = await getPatient(patientId);
    if (!patient) {
      return NextResponse.json({ error: 'Patiënt niet gevonden' }, { status: 404 });
    }

    const [intakes, encounters] = await Promise.all([
      getIntakesByPatientId(patientId).catch(() => []),
      getPatientEncounters(patientId).catch(() => []),
    ]);

    return NextResponse.json({
      patient,
      intakes,
      encounters,
    });
  } catch (error) {
    console.error('Unexpected error in GET /api/patients/[patientId]/dashboard:', error);
    return NextResponse.json(
      { error: 'Onverwachte serverfout' },
      { status: 500 }
    );
  }
}
