import type { RateData } from '../shared/types';

export const DEFAULT_RATE_DATA: RateData = {
  base: 'USD',
  pricingMode: 'mid',
  rates: {},
  sourceLabel: '',
  timestamp: '',
};

export function parseRateDataFromJson(raw: string | null | undefined): RateData {
  const json = raw || '{}';

  try {
    const parsed = JSON.parse(json) as Partial<RateData>;
    if (!parsed || typeof parsed !== 'object') {
      return DEFAULT_RATE_DATA;
    }

    return {
      base: typeof parsed.base === 'string' ? parsed.base : DEFAULT_RATE_DATA.base,
      pricingMode: parsed.pricingMode === 'bidask' ? 'bidask' : 'mid',
      rates: parsed.rates && typeof parsed.rates === 'object' ? parsed.rates : {},
      sourceLabel: typeof parsed.sourceLabel === 'string' ? parsed.sourceLabel : '',
      timestamp: typeof parsed.timestamp === 'string' ? parsed.timestamp : '',
      adjustmentPercent: typeof parsed.adjustmentPercent === 'number' ? parsed.adjustmentPercent : undefined,
      labels: parsed.labels,
    };
  } catch {
    return DEFAULT_RATE_DATA;
  }
}

export function parseRateDataScript(script: HTMLScriptElement | null): RateData {
  return parseRateDataFromJson(script?.textContent);
}
