import test from 'node:test';
import assert from 'node:assert/strict';
import { completeChat } from './llmProviderService.js';
import { OPENROUTER_DEFAULT_BASE } from './openrouterService.js';

test('completeChat with openrouter uses OpenRouter endpoint and attribution headers', async () => {
  const originalFetch = globalThis.fetch;
  let capturedUrl = '';
  const capturedHeaders: Record<string, string> = {};

  globalThis.fetch = async (url, init) => {
    capturedUrl = String(url);
    const raw = init?.headers ?? {};
    for (const [k, v] of Object.entries(raw as Record<string, string>)) {
      capturedHeaders[k.toLowerCase()] = v;
    }
    return new Response(JSON.stringify({ choices: [{ message: { content: 'OpenRouter reply' } }] }), {
      status: 200,
    });
  };

  try {
    const reply = await completeChat({
      provider: 'openrouter',
      apiKey: 'test-key',
      model: 'openai/gpt-4o-mini',
      system: 'You are helpful.',
      messages: [{ role: 'user', content: 'Hi' }],
    });
    assert.equal(reply, 'OpenRouter reply');
    assert.equal(capturedUrl, `${OPENROUTER_DEFAULT_BASE}/chat/completions`);
    assert.equal(capturedHeaders.authorization, 'Bearer test-key');
    assert.ok(capturedHeaders['http-referer']);
    assert.ok(capturedHeaders['x-title']);
  } finally {
    globalThis.fetch = originalFetch;
  }
});
