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 base ignores local-only absolute URLs in production', () => {
  for (const localApiUrl of [
    'http://localhost:3001/api/v1',
    'http://127.0.0.1:3001/api/v1',
    'http://0.0.0.0:3001/api/v1',
  ]) {
    assert.equal(
      resolveApiBase({ NODE_ENV: 'production', NEXT_PUBLIC_API_URL: localApiUrl }),
      '/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 requests include current auth user headers when a session exists', async () => {
  const originalFetch = globalThis.fetch;
  const originalSessionStorage = Object.getOwnPropertyDescriptor(globalThis, 'sessionStorage');
  const headers: HeadersInit[] = [];

  Object.defineProperty(globalThis, 'sessionStorage', {
    configurable: true,
    value: {
      getItem: (key: string) => key === 'ftb_auth_session'
        ? JSON.stringify({ id: 'm-8', name: '超级管理员', username: 'admin', roleId: 'role-admin', email: 'admin@example.com' })
        : null,
    },
  });

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

  try {
    __resetApiAvailabilityForTests();
    await api.post('/products', { name: 'FTB' });
    assert.equal((headers[1] as Record<string, string>)['x-ftb-user-id'], 'm-8');
    assert.equal((headers[1] as Record<string, string>)['x-ftb-user-role-id'], 'role-admin');
    assert.equal((headers[1] as Record<string, string>)['x-ftb-user-name'], encodeURIComponent('超级管理员'));
  } finally {
    globalThis.fetch = originalFetch;
    if (originalSessionStorage) {
      Object.defineProperty(globalThis, 'sessionStorage', originalSessionStorage);
    } else {
      delete (globalThis as any).sessionStorage;
    }
  }
});

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;
  }
});
