import { useServerVersion } from '@/api/queries'

/**
 * App version + update detection hook.
 *
 * <p>Returns:
 * <ul>
 *   <li>{@code clientVersion}, {@code clientCommit}, {@code clientBuiltAt} —
 *       built-time injected via Vite {@code define} (см. vite.config.ts).</li>
 *   <li>{@code serverVersion} — polled из {@code /api/v1/version} каждые 5 мин.</li>
 *   <li>{@code updateAvailable} — true когда client.commit ≠ server.commit AND
 *       обе stamps known (не "unknown" и не undefined).</li>
 * </ul>
 *
 * <p>Update detection conservative — игнорирует "unknown" commit (dev mode без
 * git OR before-build-info), чтобы не показывать banner ложно.
 */
export function useAppVersion() {
  const { data: server, isLoading } = useServerVersion()

  const clientCommit = __APP_COMMIT__
  const clientVersion = __APP_VERSION__
  // Empty string when build wasn't на tag pipeline. VersionBadge / UpdateBanner
  // решают priority: serverTag → clientTag → channel-based label.
  const clientTag = __APP_TAG__
  // true когда GitLab CI собрал bundle. Отличает branch build (dev) от
  // local pnpm dev (local) — оба не имеют tag'а, но семантически разные.
  const clientCI = __APP_CI__
  const clientBuiltAt = __APP_BUILT_AT__

  const knownClient = clientCommit !== 'unknown' && clientCommit !== ''
  const knownServer = Boolean(server?.commit) && server!.commit !== 'unknown'
  const updateAvailable =
    knownClient && knownServer && clientCommit !== server!.commit

  return {
    clientVersion,
    clientTag,
    clientCI,
    clientCommit,
    clientBuiltAt,
    serverVersion: server?.version,
    serverCommit: server?.commit,
    serverTag: server?.tag,
    updateAvailable,
    isLoading,
  }
}
