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

test('BLS falls back to unauthenticated v1 when configured key is invalid', async () => {
  const originalFetch = globalThis.fetch;
  const urls = [];
  globalThis.fetch = async (url) => {
    urls.push(String(url));
    if (String(url).includes('/v2/')) {
      return {
        json: async () => ({
          status: 'REQUEST_NOT_PROCESSED',
          message: ['The key:test-key provided by the User is invalid.'],
        }),
      };
    }
    return {
      json: async () => ({
        status: 'REQUEST_SUCCEEDED',
        Results: {
          series: [{
            seriesID: 'CUUR0000SA0',
            data: [{ year: '2026', period: 'M06', value: '320.1' }],
          }],
        },
      }),
    };
  };

  try {
    const { briefing } = await import('../apis/sources/bls.mjs');
    const data = await briefing('test-key');
    assert.equal(data.status, 'degraded');
    assert.match(data.configWarning, /retried with unauthenticated/);
    assert.equal(data.indicators[0].value, 320.1);
    assert.ok(urls.some(url => url.includes('/v2/')));
    assert.ok(urls.some(url => url.includes('/v1/')));
  } finally {
    globalThis.fetch = originalFetch;
  }
});

test('runSource exposes degraded warnings in timing health', async () => {
  const { runSource } = await import('../apis/briefing.mjs');
  const result = await runSource('BLS', async () => ({
    source: 'BLS',
    status: 'degraded',
    configWarning: 'Configured key rejected; fallback used.',
    indicators: [],
  }));

  assert.equal(result.status, 'degraded');
  assert.equal(result.error, 'Configured key rejected; fallback used.');
});

test('OFAC metadata uses bounded XML snippets', async () => {
  const originalFetch = globalThis.fetch;
  const requests = [];
  globalThis.fetch = async (url, options = {}) => {
    requests.push({ url: String(url), range: options.headers?.Range });
    const xml = '<sdnList><publshInformation><Publish_Date>07/07/2026</Publish_Date><Record_Count>123</Record_Count></publshInformation><sdnEntry><uid>1</uid><firstName>Jane</firstName><lastName>Example</lastName><sdnType>Individual</sdnType><program>TEST</program></sdnEntry></sdnList>';
    return new Response(xml, {
      status: 206,
      headers: { 'Content-Type': 'application/xml' },
    });
  };

  try {
    const { briefing } = await import('../apis/sources/ofac.mjs');
    const data = await briefing();
    assert.equal(data.sdnList.publishDate, '07/07/2026');
    assert.equal(data.sdnList.recordCount, 123);
    assert.equal(data.sampleEntries[0].name, 'Jane Example');
    assert.ok(requests.every(request => /^bytes=0-/.test(request.range)));
  } finally {
    globalThis.fetch = originalFetch;
  }
});
