"use client";

import { useQuery } from "@tanstack/react-query";
import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";
import { useTenantId } from "@/hooks/useTenantId";

/** Resolves the current user's patient profile for patient-portal API calls. */
export function useHealthcarePatientContext() {
  const { tenantId, loading: tenantLoading, me } = useTenantId();

  const patientsQ = useQuery({
    queryKey: ["healthcare", tenantId, "patient-context"],
    queryFn: () => healthcareApi.patients.list(tenantId!),
    enabled: !!tenantId,
  });

  const patient =
    patientsQ.data?.find((p) => p.user_id === me?.user_id) ??
    patientsQ.data?.find((p) => p.status === "active") ??
    patientsQ.data?.[0] ??
    null;

  return {
    tenantId,
    patientId: patient?.id ?? null,
    patient,
    me,
    isLoading: tenantLoading || patientsQ.isLoading,
    error: patientsQ.error,
    refetch: patientsQ.refetch,
  };
}
