"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 doctor profile for doctor-panel API calls. */
export function useHealthcareDoctorContext() {
  const { tenantId, loading: tenantLoading, me } = useTenantId();

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

  const doctor =
    doctorsQ.data?.find((d) => d.user_id === me?.user_id) ??
    doctorsQ.data?.find((d) => d.status === "active") ??
    doctorsQ.data?.[0] ??
    null;

  return {
    tenantId,
    doctorId: doctor?.id ?? null,
    doctor,
    me,
    isLoading: tenantLoading || doctorsQ.isLoading,
    error: doctorsQ.error,
    refetch: doctorsQ.refetch,
  };
}
