/**
 * Resource Inventory Service Tests
 */

import { describe, it, expect, beforeEach, vi } from 'vitest'
import * as inventoryService from '../resource-inventory'
import type { Context } from '../../types/context'

describe('Resource Inventory Service', () => {
  let mockContext: Context
  let mockDb: any

  beforeEach(() => {
    mockDb = {
      query: vi.fn(),
    }

    mockContext = {
      db: mockDb as any,
      user: {
        id: 'user-1',
        email: 'test@example.com',
        name: 'Test User',
        role: 'ADMIN',
      },
    } as Context
  })

  describe('getResourceInventory', () => {
    it('should return inventory items', async () => {
      const mockRows = [{
        id: 'inv-1',
        resource_type: 'VM',
        provider: 'PROXMOX',
        provider_id: 'node:100',
        name: 'test-vm',
        region: 'us-east-1',
        site_id: 'site-1',
        metadata: JSON.stringify({ cpu: 4 }),
        tags: JSON.stringify(['production']),
        discovered_at: new Date(),
        last_synced_at: new Date(),
        created_at: new Date(),
        updated_at: new Date(),
      }]

      mockDb.query.mockResolvedValue({ rows: mockRows })

      const result = await inventoryService.getResourceInventory(mockContext)

      expect(result).toHaveLength(1)
      expect(result[0].name).toBe('test-vm')
    })

    it('should filter by provider', async () => {
      mockDb.query.mockResolvedValue({ rows: [] })

      await inventoryService.getResourceInventory(mockContext, { provider: 'PROXMOX' })

      expect(mockDb.query).toHaveBeenCalledWith(
        expect.stringContaining('provider = $1'),
        ['PROXMOX']
      )
    })
  })

  describe('upsertResourceInventoryItem', () => {
    it('should create new item when not exists', async () => {
      // Mock getResourceInventoryByProvider to return null (doesn't exist)
      mockDb.query
        .mockResolvedValueOnce({ rows: [] }) // getResourceInventoryByProvider
        .mockResolvedValueOnce({
          rows: [{
            id: 'inv-1',
            resource_type: 'VM',
            provider: 'PROXMOX',
            provider_id: 'node:100',
            name: 'test-vm',
            metadata: JSON.stringify({}),
            tags: JSON.stringify([]),
            discovered_at: new Date(),
            last_synced_at: new Date(),
            created_at: new Date(),
            updated_at: new Date(),
          }],
        }) // INSERT

      const input = {
        resourceType: 'VM',
        provider: 'PROXMOX',
        providerId: 'node:100',
        name: 'test-vm',
      }

      const result = await inventoryService.upsertResourceInventoryItem(mockContext, input)

      expect(result).toBeDefined()
      expect(result.name).toBe('test-vm')
    })
  })
})

