import { useSubscription } from '@apollo/client'
import {
  RESOURCE_UPDATED,
  METRICS_UPDATED,
  HEALTH_CHANGED,
  FINDING_CREATED,
  RISK_CREATED,
} from '../subscriptions'

/**
 * Hook for subscribing to resource updates
 */
export function useResourceUpdate(resourceId: string) {
  const { data, loading, error } = useSubscription(RESOURCE_UPDATED, {
    variables: { resourceId },
    skip: !resourceId,
  })

  return {
    resource: data?.resourceUpdated,
    loading,
    error,
  }
}

/**
 * Hook for subscribing to metrics updates
 */
export function useMetricsUpdate(resourceId: string, metricType: string) {
  const { data, loading, error } = useSubscription(METRICS_UPDATED, {
    variables: { resourceId, metricType },
    skip: !resourceId || !metricType,
  })

  return {
    metric: data?.metricsUpdated,
    loading,
    error,
  }
}

/**
 * Hook for subscribing to health changes
 */
export function useHealthChange(resourceId: string) {
  const { data, loading, error } = useSubscription(HEALTH_CHANGED, {
    variables: { resourceId },
    skip: !resourceId,
  })

  return {
    health: data?.healthChanged,
    loading,
    error,
  }
}

/**
 * Hook for subscribing to new findings
 */
export function useFindingCreated(controlId?: string) {
  const { data, loading, error } = useSubscription(FINDING_CREATED, {
    variables: { controlId: controlId || null },
  })

  return {
    finding: data?.findingCreated,
    loading,
    error,
  }
}

/**
 * Hook for subscribing to new risks
 */
export function useRiskCreated(resourceId?: string) {
  const { data, loading, error } = useSubscription(RISK_CREATED, {
    variables: { resourceId: resourceId || null },
  })

  return {
    risk: data?.riskCreated,
    loading,
    error,
  }
}

