/**
 * Prometheus Adapter Tests
 */

import { describe, it, expect, beforeEach, vi } from 'vitest'
import { PrometheusAdapter } from '../monitoring/prometheus-adapter'

// Mock fetch globally
global.fetch = vi.fn()

describe('PrometheusAdapter', () => {
  let adapter: PrometheusAdapter

  beforeEach(() => {
    adapter = new PrometheusAdapter({
      url: 'http://localhost:9090',
    })
    vi.clearAllMocks()
  })

  describe('query', () => {
    it('should execute Prometheus queries', async () => {
      const mockResponse = {
        status: 'success',
        data: {
          resultType: 'vector',
          result: [
            {
              metric: { instance: 'localhost:9090' },
              value: [Math.floor(Date.now() / 1000), '100'],
            },
          ],
        },
      }

      ;(global.fetch as any).mockResolvedValue({
        ok: true,
        json: async () => mockResponse,
      })

      const result = await adapter.query('up')

      expect(result).toBeDefined()
      expect(result.length).toBeGreaterThan(0)
      expect(global.fetch).toHaveBeenCalledWith(
        expect.stringContaining('/api/v1/query'),
        expect.any(Object)
      )
    })

    it('should handle query errors', async () => {
      ;(global.fetch as any).mockResolvedValue({
        ok: true,
        json: async () => ({
          status: 'error',
          error: 'Invalid query',
        }),
      })

      await expect(adapter.query('invalid query')).rejects.toThrow()
    })
  })

  describe('queryRange', () => {
    it('should execute range queries', async () => {
      const mockResponse = {
        status: 'success',
        data: {
          resultType: 'matrix',
          result: [
            {
              metric: { instance: 'localhost:9090' },
              values: [
                [Math.floor(Date.now() / 1000) - 60, '100'],
                [Math.floor(Date.now() / 1000), '110'],
              ],
            },
          ],
        },
      }

      ;(global.fetch as any).mockResolvedValue({
        ok: true,
        json: async () => mockResponse,
      })

      const result = await adapter.queryRange(
        'up',
        new Date(Date.now() - 3600000),
        new Date(),
        '15s'
      )

      expect(result).toBeDefined()
      expect(result.length).toBeGreaterThan(0)
    })
  })
})

