import assert from 'node:assert/strict';
import test from 'node:test';

import { __resetApiAvailabilityForTests, api, resolveApiBase } from './api';

test('API base defaults to same-origin in production and localhost in development', () => {
  assert.equal(resolveApiBase({ NODE_ENV: 'production' }), '/api/v1');
  assert.equal(resolveApiBase({ NODE_ENV: 'development' }), 'http://localhost:3001/api/v1');
  assert.equal(
    resolveApiBase({ NODE_ENV: 'production', NEXT_PUBLIC_API_URL: 'https://api.example.com/api/v1/' }),
    'https://api.example.com/api/v1',
  );
});

test('API requests use the resolved base path', async () => {
  const originalFetch = globalThis.fetch;
  const apiBase = resolveApiBase();
  const urls: string[] = [];

  globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
    urls.push(String(input));
    return new Response(JSON.stringify(init?.method === 'POST' ? { ok: true } : {}), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    });
  }) as typeof fetch;

  try {
    __resetApiAvailabilityForTests();
    await api.post('/config/ai/test', { id: 'provider-1' });
    assert.deepEqual(urls, [`${apiBase}/config/ai`, `${apiBase}/config/ai/test`]);
  } finally {
    globalThis.fetch = originalFetch;
  }
});

test('API availability probe retries after a transient failure', async () => {
  const originalFetch = globalThis.fetch;
  const apiBase = resolveApiBase();
  const calls: string[] = [];

  globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
    calls.push(String(input));
    if (calls.length === 1) throw new Error('temporary network failure');
    return new Response(JSON.stringify(init?.method === 'POST' ? { ok: true } : {}), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    });
  }) as typeof fetch;

  try {
    __resetApiAvailabilityForTests();
    await assert.rejects(() => api.post('/config/ai/test', { id: 'provider-1' }), /API 不可用/);
    await api.post('/config/ai/test', { id: 'provider-1' });
    assert.deepEqual(calls, [
      `${apiBase}/config/ai`,
      `${apiBase}/config/ai`,
      `${apiBase}/config/ai/test`,
    ]);
  } finally {
    globalThis.fetch = originalFetch;
  }
});
