import { useQuery } from '@tanstack/react-query'
import client from '../api/client'

/**
 * Polls /api/system/status every 5 minutes to stay in sync with the backend
 * heartbeat cycle. Returns a stable object so callers can destructure safely.
 *
 * Returned shape:
 *   licensed          bool
 *   locked            bool
 *   lock_pending      bool
 *   lock_reason       "admin" | "expired" | null
 *   expires_at        string | null   (ISO)
 *   days_until_expiry number | null   (negative = expired)
 *   grace_expires_at  string | null   (ISO)
 *   grace_days_remaining number | null
 *   sync_failed       bool
 *
 * Derived helpers:
 *   showExpiryWarning bool  — true when 0 < days_until_expiry <= 5
 *   inGracePeriod     bool  — true when expired but grace not yet over
 *   isBlocked         bool  — locked=true OR (unlicensed AND grace over)
 */
export default function useLicenseStatus() {
  const { data } = useQuery({
    queryKey: ['license-status'],
    queryFn: () => client.get('/api/system/status').then(r => r.data),
    staleTime: 0,
    refetchInterval: 5 * 60 * 1000,
    refetchIntervalInBackground: true,
  })

  if (!data) {
    return {
      licensed: true,
      locked: false,
      lock_pending: false,
      lock_reason: null,
      expires_at: null,
      days_until_expiry: null,
      grace_expires_at: null,
      grace_days_remaining: null,
      sync_failed: false,
      showExpiryWarning: false,
      inGracePeriod: false,
      isBlocked: false,
    }
  }

  const {
    licensed = true,
    locked = false,
    lock_pending = false,
    lock_reason = null,
    expires_at = null,
    days_until_expiry = null,
    grace_expires_at = null,
    grace_days_remaining = null,
    sync_failed = false,
  } = data

  const showExpiryWarning =
    days_until_expiry != null && days_until_expiry >= 0 && days_until_expiry <= 5

  const inGracePeriod =
    days_until_expiry != null && days_until_expiry < 0 && licensed

  const isBlocked = locked || !licensed

  return {
    licensed,
    locked,
    lock_pending,
    lock_reason,
    expires_at,
    days_until_expiry,
    grace_expires_at,
    grace_days_remaining,
    sync_failed,
    showExpiryWarning,
    inGracePeriod,
    isBlocked,
  }
}
