import { useMutation, useQuery } from '@tanstack/react-query';
import api from '@/lib/api';
import type { Scenario, MetricSummary } from '@/types/api';

const COMPARISON_KEY = 'comparison';

export interface ComparisonScenario {
  scenario: Scenario;
  summary: MetricSummary;
}

export interface ComparisonResult {
  scenarios: ComparisonScenario[];
  deltas: Record<string, { value: number; percentage: number }[]>;
}

export interface CompareRequest {
  scenario_ids: string[];
  metrics?: string[];
}

export function useCompareScenarios() {
  return useMutation<ComparisonResult, Error, CompareRequest>({
    mutationFn: async (data) => {
      const response = await api.post('/scenarios/compare', data);
      return response.data;
    },
  });
}

export function useComparisonCache(scenarioIds: string[]) {
  return useQuery<ComparisonResult>({
    queryKey: [COMPARISON_KEY, scenarioIds.sort().join(',')],
    queryFn: async () => {
      const response = await api.post('/scenarios/compare', {
        scenario_ids: scenarioIds,
      });
      return response.data;
    },
    enabled: scenarioIds.length >= 2 && scenarioIds.length <= 4,
    staleTime: 5 * 60 * 1000, // 5 minutes cache
  });
}
