import { describe, expect, it, vi, beforeAll, afterAll } from 'vitest';
import { createServiceApp, type FastifyApp } from '@bytelyst/fastify-core';

vi.mock('../../lib/config.js', () => ({
  config: {
    SERVICE_NAME: 'cowork-service',
    PLATFORM_SERVICE_URL: 'http://localhost:4003',
  },
}));
vi.mock('../../lib/product-config.js', () => ({
  PRODUCT_ID: 'clawcowork',
}));
vi.mock('../../lib/ipc-bridge.js', () => ({
  getIpcBridge: vi.fn(() => ({ isRunning: false })),
}));

import { healthRoutes } from './routes.js';
import { getIpcBridge } from '../../lib/ipc-bridge.js';

let app: FastifyApp;

beforeAll(async () => {
  app = await createServiceApp({
    name: 'cowork-health-test',
    version: '0.0.1',
    logger: false,
  });
  await app.register(healthRoutes);
});

afterAll(async () => {
  await app.close();
});

describe('health routes', () => {
  it('GET /api/health/dependencies — returns degraded when IPC bridge is disconnected', async () => {
    const res = await app.inject({
      method: 'GET',
      url: '/api/health/dependencies',
    });

    // Platform-service unreachable + IPC disconnected → 503
    expect(res.statusCode).toBe(503);
    const body = JSON.parse(res.payload);
    expect(body.status).toBe('degraded');
    expect(body.service).toBe('cowork-service');
    expect(body.productId).toBe('clawcowork');
    expect(body.ipcBridge).toBe('disconnected');
    expect(body.checks).toHaveProperty('platform-service');
    expect(body.timestamp).toBeDefined();
  });

  it('GET /api/health/dependencies — reports ipcBridge connected when bridge is running', async () => {
    vi.mocked(getIpcBridge).mockReturnValue({ isRunning: true } as ReturnType<typeof getIpcBridge>);

    const res = await app.inject({
      method: 'GET',
      url: '/api/health/dependencies',
    });

    const body = JSON.parse(res.payload);
    expect(body.ipcBridge).toBe('connected');
    expect(body.productId).toBe('clawcowork');
    // Overall status depends on platform-service reachability — just verify field exists
    expect(['ok', 'degraded']).toContain(body.status);

    // Reset
    vi.mocked(getIpcBridge).mockReturnValue({ isRunning: false } as ReturnType<typeof getIpcBridge>);
  });
});
