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

const SCENARIOS_KEY = 'scenarios';

export function useScenarios(page = 1, pageSize = 20, status?: string, region?: string) {
  return useQuery<ScenarioList>({
    queryKey: [SCENARIOS_KEY, page, pageSize, status, region],
    queryFn: async () => {
      const params = new URLSearchParams();
      params.append('page', page.toString());
      params.append('page_size', pageSize.toString());
      if (status) params.append('status', status);
      if (region) params.append('region', region);
      
      const response = await api.get(`/scenarios?${params.toString()}`);
      return response.data;
    },
  });
}

export function useScenario(id: string) {
  return useQuery<Scenario>({
    queryKey: [SCENARIOS_KEY, id],
    queryFn: async () => {
      const response = await api.get(`/scenarios/${id}`);
      return response.data;
    },
    enabled: !!id,
  });
}

export function useCreateScenario() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async (data: ScenarioCreate) => {
      const response = await api.post('/scenarios', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [SCENARIOS_KEY] });
    },
  });
}

export function useUpdateScenario(id: string) {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async (data: ScenarioUpdate) => {
      const response = await api.put(`/scenarios/${id}`, data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [SCENARIOS_KEY] });
      queryClient.invalidateQueries({ queryKey: [SCENARIOS_KEY, id] });
    },
  });
}

export function useDeleteScenario() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async (id: string) => {
      await api.delete(`/scenarios/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [SCENARIOS_KEY] });
    },
  });
}

export function useStartScenario(id: string) {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async () => {
      const response = await api.post(`/scenarios/${id}/start`);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [SCENARIOS_KEY, id] });
    },
  });
}

export function useStopScenario(id: string) {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async () => {
      const response = await api.post(`/scenarios/${id}/stop`);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [SCENARIOS_KEY, id] });
    },
  });
}
