
const chartHostUrls = [
  '*://chart.tradenation.com/*',
  '*://chart-cfd.tradenation.com/*',
  '*://demochart.tradenation.com/*',
];

const tfcApiEndpoints = new Set([
  'https://licensing.tradefromchart.com/tfc/licensing',
  'https://api.tradefromchart.com/tfc/trk',
  'https://api.tradefromchart.com/tfc/trkst',
  'https://api.tradefromchart.com/tfc/checkupdate',
  'https://api.tradefromchart.com/tfc/calendar',
  'https://api.tradefromchart.com/tfc/news',
  'https://api.tradefromchart.com/tfc/pastsignals',
  'https://api.tradefromchart.com/tfc/pasttrumpsignals',
  'https://api.tradefromchart.com/tfc/ovrangedatanew2',
  'https://api.tradefromchart.com/tfc/cnbc',
]);

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (!message || message.type !== 'tfc-extension-fetch') return false;

  if (!tfcApiEndpoints.has(message.url)) {
    sendResponse({
      id: message.id,
      ok: false,
      error: `Blocked extension fetch URL: ${message.url}`,
    });
    return false;
  }

  let body;
  if (typeof message.body === 'string') {
    body = message.body;
  } else if (message.body && typeof message.body === 'object' && Object.keys(message.body).length) {
    body = JSON.stringify(message.body);
  }

  fetch(message.url, {
    method: 'POST',
    body,
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(response => response.text().then(text => {
      try {
        return text ? JSON.parse(text) : {};
      } catch (error) {
        throw new Error(`Non-JSON response from ${message.url}: ${text.slice(0, 120)}`);
      }
    }))
    .then(data => {
      sendResponse({
        id: message.id,
        ok: true,
        data,
      });
    })
    .catch(error => {
      sendResponse({
        id: message.id,
        ok: false,
        error: error && error.message ? error.message : String(error),
      });
    });

  return true;
});

// Keeps the MV3 service worker warm for chart-page extension messages.
chrome.webRequest.onBeforeSendHeaders.addListener(
  () => {},
  { urls: chartHostUrls },
  ['requestHeaders', 'extraHeaders'],
);

chrome.declarativeNetRequest.getDynamicRules(previousRules => {
  const previousRuleIds = previousRules.map(rule => rule.id);
  chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: previousRuleIds,
    addRules: []
  }, () => {
    if (chrome.runtime.lastError) {
      console.error('[tfc-background] dynamic DNR registration failed:', chrome.runtime.lastError.message);
    }
  });
});
