'use client';

/**
 * React Query hooks for the Website Analytics page. Mirrors the structure
 * of `src/components/dashboard/use-analytics.ts` but talks to the Umami
 * proxy at /api/v1/website-analytics.
 *
 * All hooks are gated on `currentPortId` so they don't fire before the
 * port is resolved (which would cause a 401 to land in the React Query
 * cache and persist as `isError: true` until staleTime expires).
 */

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

import { apiFetch } from '@/lib/api/client';
import { useUIStore } from '@/stores/ui-store';
import { isCustomRange, type DateRange } from '@/lib/analytics/range';
import type {
  UmamiActiveVisitors,
  UmamiMetricRow,
  UmamiPageviewsSeries,
  UmamiStats,
} from '@/lib/services/umami.service';

interface MetricResponse<T> {
  metric: string;
  range: DateRange;
  data: T | null;
  /** True when Umami isn't configured for the port. Surfaced as a 200
   *  response (not 4xx) so React Query doesn't infinitely retry — that
   *  retry loop previously saturated the postgres pool and hung the dev
   *  server. UI consumers should check this flag and render the
   *  "set up Umami" empty state. */
  notConfigured?: boolean;
}

function rangeToQuery(range: DateRange): string {
  if (isCustomRange(range)) {
    return `range=custom&from=${range.from}&to=${range.to}`;
  }
  return `range=${range}`;
}

function useUmamiQuery<T>(
  metric: string,
  range: DateRange,
  extraParams = '',
  /** Override the cache key segment that defaults to `range`. Use for
   *  metrics whose response is range-independent (e.g. active visitors)
   *  so the cache isn't fragmented across each date the user has picked. */
  cacheKeySegment?: unknown,
) {
  const portId = useUIStore((s) => s.currentPortId);
  return useQuery<MetricResponse<T>>({
    queryKey: ['website-analytics', metric, cacheKeySegment ?? range, portId],
    queryFn: () =>
      apiFetch<MetricResponse<T>>(
        `/api/v1/website-analytics?metric=${metric}&${rangeToQuery(range)}${extraParams}`,
      ),
    staleTime: 30_000, // umami data refreshes constantly; short stale time
    retry: 1,
    enabled: !!portId,
  });
}

export const useUmamiStats = (range: DateRange) => useUmamiQuery<UmamiStats>('stats', range);
export const useUmamiPageviews = (range: DateRange) =>
  useUmamiQuery<UmamiPageviewsSeries>('pageviews', range);

// Active visitors are server-side range-independent (Umami's /active endpoint
// returns the last-5-minute count regardless of what range we pass). Use a
// fixed cache-key segment so the dashboard tile (range='today') and the
// website-analytics shell (any selected range) share one cache entry instead
// of fragmenting it across every range the user picks.
export const useUmamiActive = (range: DateRange) =>
  useUmamiQuery<UmamiActiveVisitors>('active', range, '', 'fixed');

export const useUmamiTopPages = (range: DateRange, limit = 10) =>
  useUmamiQuery<UmamiMetricRow[]>('top-url', range, `&limit=${limit}`);
export const useUmamiTopReferrers = (range: DateRange, limit = 10) =>
  useUmamiQuery<UmamiMetricRow[]>('top-referrer', range, `&limit=${limit}`);
export const useUmamiTopCountries = (range: DateRange, limit = 10) =>
  useUmamiQuery<UmamiMetricRow[]>('top-country', range, `&limit=${limit}`);
