import { describe, expect, it } from 'vitest';

import { buildOpsCockpit } from '@/lib/ops-cockpit';

describe('buildOpsCockpit', () => {
  it('prioritizes down restartable services and degraded cache health for the operator', () => {
    const cockpit = buildOpsCockpit({
      status: {
        overall: 'critical',
        timestamp: '2026-05-30T00:00:00Z',
        services: [
          {
            id: 'admin-web',
            name: 'Admin Web',
            group: 'dashboards',
            target: 'http://127.0.0.1:3001',
            status: 'healthy',
            latency: 42,
            lastChecked: '2026-05-30T00:00:00Z',
          },
          {
            id: 'freellmapi',
            name: 'FreeLLMAPI',
            group: 'llm',
            target: 'http://127.0.0.1:3001/v1',
            status: 'down',
            latency: 900,
            message: 'connection refused',
            lastChecked: '2026-05-30T00:00:00Z',
          },
        ],
      },
      inventory: {
        timestamp: '2026-05-30T00:00:00Z',
        counts: { services: 2, healthy: 1, degraded: 0, down: 1, hostTools: 2 },
        services: [
          {
            id: 'freellmapi',
            name: 'FreeLLMAPI',
            group: 'llm',
            target: 'http://127.0.0.1:3001/v1',
            status: 'down',
            latency: 900,
            description: 'Local LLM fallback gateway',
            management: 'vm',
            exposure: 'internal',
            restartable: true,
            lastChecked: '2026-05-30T00:00:00Z',
          },
        ],
        hostTools: [],
      },
      valkey: {
        timestamp: '2026-05-30T00:00:00Z',
        pattern: '*',
        limit: 25,
        summary: {
          ping: 'PONG',
          dbsize: 123,
          matchedKeys: 25,
          version: '7.2',
          usedMemoryHuman: '1M',
          usedMemoryPeakHuman: '8M',
        },
        keys: [],
      },
    });

    expect(cockpit.headline).toContain('Critical');
    expect(cockpit.priorityActions[0]).toMatchObject({
      serviceId: 'freellmapi',
      action: 'Restart service',
      severity: 'critical',
    });
    expect(cockpit.tiles).toContainEqual(
      expect.objectContaining({ label: 'Restartable issues', value: '1' })
    );
  });

  it('returns a calm checklist when everything is healthy', () => {
    const cockpit = buildOpsCockpit({ status: null, inventory: null, valkey: null });

    expect(cockpit.headline).toBe('Waiting for live ops telemetry');
    expect(cockpit.priorityActions).toHaveLength(1);
    expect(cockpit.priorityActions[0].action).toBe('Refresh telemetry');
  });
});
