import {
  describe,
  expect,
  it,
  vi
} from 'vitest';
import { probeSignalingEndpointHealth, resolveSignalingHttpBaseUrl } from './signaling-endpoint-health.rules';

describe('signaling endpoint health rules', () => {
  it('maps websocket urls to http health bases', () => {
    expect(resolveSignalingHttpBaseUrl('wss://46.59.68.77:3001/ws')).toBe('https://46.59.68.77:3001');
    expect(resolveSignalingHttpBaseUrl('ws://localhost:3001')).toBe('http://localhost:3001');
  });

  it('treats unreachable endpoints as unhealthy', async () => {
    const fetchFn = vi.fn(async () => {
      throw new Error('network down');
    });

    await expect(probeSignalingEndpointHealth('ws://localhost:3001', { fetchFn })).resolves.toEqual({ ok: false });
  });

  it('accepts /api/health and falls back to /api/servers', async () => {
    const fetchFn = vi.fn(async (url: string) => {
      if (url.endsWith('/api/health')) {
        return new Response(null, { status: 503 });
      }

      if (url.endsWith('/api/servers')) {
        return new Response('[]', { status: 200 });
      }

      throw new Error(`unexpected url: ${url}`);
    });

    await expect(probeSignalingEndpointHealth('ws://localhost:3001', { fetchFn })).resolves.toEqual({ ok: true });
    expect(fetchFn).toHaveBeenCalledTimes(2);
  });

  it('returns serverInstanceId from /api/health when available', async () => {
    const fetchFn = vi.fn(async (url: string) => {
      if (url.endsWith('/api/health')) {
        return new Response(JSON.stringify({ serverInstanceId: 'instance-a' }), { status: 200 });
      }

      throw new Error(`unexpected url: ${url}`);
    });

    await expect(probeSignalingEndpointHealth('ws://localhost:3001', { fetchFn })).resolves.toEqual({
      ok: true,
      serverInstanceId: 'instance-a'
    });
  });
});
