'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useSession } from 'next-auth/react';

import {
  getInfraNodes,
  getInfraStorage,
  getVMs,
  getHealthSummary,
  getHealthAlerts,
  getTenantResources,
  getTenantHealth,
  vmAction,
} from '@/lib/phoenix-api-client';

export function usePhoenixInfraNodes() {
  const { data: session } = useSession();
  const token = session?.accessToken;
  return useQuery({
    queryKey: ['phoenix', 'infra', 'nodes'],
    queryFn: () => getInfraNodes(token),
    enabled: !!token,
  });
}

export function usePhoenixInfraStorage() {
  const { data: session } = useSession();
  const token = session?.accessToken;
  return useQuery({
    queryKey: ['phoenix', 'infra', 'storage'],
    queryFn: () => getInfraStorage(token),
    enabled: !!token,
  });
}

export function usePhoenixVMs(node?: string) {
  const { data: session } = useSession();
  const token = session?.accessToken;
  return useQuery({
    queryKey: ['phoenix', 've', 'vms', node],
    queryFn: () => getVMs(token, node),
    enabled: !!token,
  });
}

export function usePhoenixHealthSummary() {
  const { data: session } = useSession();
  const token = session?.accessToken;
  return useQuery({
    queryKey: ['phoenix', 'health', 'summary'],
    queryFn: () => getHealthSummary(token),
    enabled: !!token,
    refetchInterval: 60000,
  });
}

export function usePhoenixHealthAlerts() {
  const { data: session } = useSession();
  const token = session?.accessToken;
  return useQuery({
    queryKey: ['phoenix', 'health', 'alerts'],
    queryFn: () => getHealthAlerts(token),
    enabled: !!token,
    refetchInterval: 30000,
  });
}

export function useTenantResources() {
  const { data: session } = useSession();
  const token = session?.accessToken;
  return useQuery({
    queryKey: ['phoenix', 'tenants', 'me', 'resources'],
    queryFn: () => getTenantResources(token),
    enabled: !!token,
  });
}

export function useTenantHealth() {
  const { data: session } = useSession();
  const token = session?.accessToken;
  return useQuery({
    queryKey: ['phoenix', 'tenants', 'me', 'health'],
    queryFn: () => getTenantHealth(token),
    enabled: !!token,
  });
}

export function useVMAction() {
  const { data: session } = useSession();
  const token = session?.accessToken;
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ node, vmid, action, type }: { node: string; vmid: string; action: 'start' | 'stop' | 'reboot'; type?: 'qemu' | 'lxc' }) =>
      vmAction(node, vmid, action, token, type || 'qemu'),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['phoenix', 've', 'vms'] });
    },
  });
}
