'use client';

import { useQuery } from '@tanstack/react-query';

import { apiFetch } from '@/lib/api/client';
import type {
  DateRange,
  LeadSourceAttributionData,
  MetricBase,
  OccupancyTimelineData,
  PipelineFunnelData,
  RevenueBreakdownData,
} from '@/lib/services/analytics.service';

interface MetricResponse<T> {
  metric: MetricBase;
  range: DateRange;
  data: T;
}

export function useAnalyticsMetric<T>(metric: MetricBase, range: DateRange) {
  return useQuery<T>({
    queryKey: ['analytics', metric, range],
    queryFn: async () => {
      const res = await apiFetch<MetricResponse<T>>(
        `/api/v1/analytics?metric=${metric}&range=${range}`,
      );
      return res.data;
    },
    staleTime: 60_000,
    retry: 2,
  });
}

export const useFunnel = (range: DateRange) =>
  useAnalyticsMetric<PipelineFunnelData>('pipeline_funnel', range);
export const useOccupancy = (range: DateRange) =>
  useAnalyticsMetric<OccupancyTimelineData>('occupancy_timeline', range);
export const useRevenue = (range: DateRange) =>
  useAnalyticsMetric<RevenueBreakdownData>('revenue_breakdown', range);
export const useLeadSource = (range: DateRange) =>
  useAnalyticsMetric<LeadSourceAttributionData>('lead_source_attribution', range);
