import { useQuery } from '@apollo/client'
import { GET_SYSTEM_HEALTH, GET_COST_OVERVIEW, GET_BILLING_INFO, GET_API_USAGE, GET_DEPLOYMENTS, GET_TEST_ENVIRONMENTS, GET_API_KEYS } from '@/lib/graphql/queries/dashboard'
import { useSession } from 'next-auth/react'

export function useSystemHealth() {
  return useQuery(GET_SYSTEM_HEALTH, {
    pollInterval: 30000, // Poll every 30 seconds
    errorPolicy: 'all',
  })
}

export function useCostOverview(tenantId?: string) {
  const { data: session } = useSession()
  const defaultTenantId = tenantId || (session as any)?.tenantId

  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)

  return useQuery(GET_COST_OVERVIEW, {
    variables: {
      tenantId: defaultTenantId || 'default',
      timeRange: {
        start: startDate.toISOString(),
        end: endDate.toISOString(),
      },
    },
    skip: !defaultTenantId,
    errorPolicy: 'all',
  })
}

export function useBillingInfo(tenantId?: string) {
  const { data: session } = useSession()
  const defaultTenantId = tenantId || (session as any)?.tenantId

  return useQuery(GET_BILLING_INFO, {
    variables: {
      tenantId: defaultTenantId || 'default',
    },
    skip: !defaultTenantId,
    errorPolicy: 'all',
  })
}

export function useAPIUsage() {
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 7)

  return useQuery(GET_API_USAGE, {
    variables: {
      timeRange: {
        start: startDate.toISOString(),
        end: endDate.toISOString(),
      },
    },
    pollInterval: 60000, // Poll every minute
    errorPolicy: 'all',
  })
}

export function useDeployments(filter?: { status?: string; limit?: number }) {
  return useQuery(GET_DEPLOYMENTS, {
    variables: {
      filter: filter || { limit: 10 },
    },
    pollInterval: 30000,
    errorPolicy: 'all',
  })
}

export function useTestEnvironments() {
  return useQuery(GET_TEST_ENVIRONMENTS, {
    pollInterval: 30000,
    errorPolicy: 'all',
  })
}

export function useAPIKeys() {
  return useQuery(GET_API_KEYS, {
    errorPolicy: 'all',
  })
}

