import { DEFAULT_RATE_DATA, parseRateDataFromJson, parseRateDataScript } from './rate-data';

describe('parseRateDataFromJson', () => {
  it('returns normalized rate data for valid payload', () => {
    const raw = JSON.stringify({
      base: 'EUR',
      pricingMode: 'bidask',
      rates: { USD: { mid: 1.2, bid: 1.19, ask: 1.21 } },
      sourceLabel: 'EUCB',
      timestamp: '2026-02-17T10:00:00Z',
      adjustmentPercent: 1.25,
      labels: {
        mid: { from: 'From', to: 'To' },
      },
    });

    const parsed = parseRateDataFromJson(raw);

    expect(parsed.base).toBe('EUR');
    expect(parsed.pricingMode).toBe('bidask');
    expect(parsed.sourceLabel).toBe('EUCB');
    expect(parsed.timestamp).toBe('2026-02-17T10:00:00Z');
    expect(parsed.adjustmentPercent).toBe(1.25);
    expect(parsed.rates).toEqual({ USD: { mid: 1.2, bid: 1.19, ask: 1.21 } });
  });

  it('returns defaults for malformed JSON', () => {
    expect(parseRateDataFromJson('{broken-json')).toBe(DEFAULT_RATE_DATA);
  });

  it('returns defaults for non-object payload', () => {
    expect(parseRateDataFromJson('"abc"')).toBe(DEFAULT_RATE_DATA);
  });

  it('uses safe fallbacks for missing/invalid fields', () => {
    const parsed = parseRateDataFromJson(
      JSON.stringify({
        base: 10,
        pricingMode: 'unknown',
        rates: 'bad',
        sourceLabel: 99,
        timestamp: false,
        adjustmentPercent: '2',
      })
    );

    expect(parsed.base).toBe(DEFAULT_RATE_DATA.base);
    expect(parsed.pricingMode).toBe('mid');
    expect(parsed.rates).toEqual({});
    expect(parsed.sourceLabel).toBe('');
    expect(parsed.timestamp).toBe('');
    expect(parsed.adjustmentPercent).toBeUndefined();
  });
});

describe('parseRateDataScript', () => {
  it('reads JSON from script text content', () => {
    const script = document.createElement('script');
    script.textContent = JSON.stringify({ base: 'GBP' });

    expect(parseRateDataScript(script).base).toBe('GBP');
  });

  it('falls back to defaults when script is null', () => {
    expect(parseRateDataScript(null)).toEqual({
      ...DEFAULT_RATE_DATA,
      adjustmentPercent: undefined,
      labels: undefined,
    });
  });
});
