import { describe, it, expect, vi } from 'vitest';
import { resolveProjectLlmReference } from '../src/discovery.js';
import type { McpdClient } from '../src/http/mcpd-client.js';

function mockClient(get: (path: string) => Promise<unknown>): McpdClient {
  return { get } as unknown as McpdClient;
}

describe('resolveProjectLlmReference', () => {
  it('returns "disabled" for the literal string "none"', async () => {
    const client = mockClient(async () => { throw new Error('should not be called'); });
    expect(await resolveProjectLlmReference(client, 'none')).toBe('disabled');
  });

  it('returns "unregistered" when llmProvider is empty or undefined', async () => {
    const client = mockClient(async () => { throw new Error('should not be called'); });
    expect(await resolveProjectLlmReference(client, undefined)).toBe('unregistered');
    expect(await resolveProjectLlmReference(client, '')).toBe('unregistered');
  });

  it('returns "registered" when mcpd returns 200 for the name', async () => {
    const get = vi.fn(async () => ({ name: 'claude' }));
    expect(await resolveProjectLlmReference(mockClient(get), 'claude')).toBe('registered');
    expect(get).toHaveBeenCalledWith('/api/v1/llms/claude');
  });

  it('returns "unregistered" on 404', async () => {
    const client = mockClient(async () => { throw new Error('HTTP 404 not found'); });
    expect(await resolveProjectLlmReference(client, 'missing')).toBe('unregistered');
  });

  it('returns "unreachable" on other errors (500, network)', async () => {
    const client = mockClient(async () => { throw new Error('HTTP 500 internal error'); });
    expect(await resolveProjectLlmReference(client, 'x')).toBe('unreachable');

    const client2 = mockClient(async () => { throw new Error('ECONNREFUSED'); });
    expect(await resolveProjectLlmReference(client2, 'x')).toBe('unreachable');
  });

  it('URL-encodes names with special characters', async () => {
    const get = vi.fn(async () => ({}));
    await resolveProjectLlmReference(mockClient(get), 'weird name/with/slashes');
    expect(get).toHaveBeenCalledWith('/api/v1/llms/weird%20name%2Fwith%2Fslashes');
  });
});
