const axios = require('axios');
const logger = require('./logger');

async function sendWebhook(url, secret, payload) {
  if (!url) {
    logger.info('WEBHOOK_URL not set, skipping notification');
    return { skipped: true };
  }

  const headers = { 'Content-Type': 'application/json' };
  if (secret) {
    headers['X-Webhook-Secret'] = secret;
  }

  const response = await axios.post(url, payload, {
    headers,
    timeout: 10000,
    validateStatus: () => true
  });

  if (response.status >= 200 && response.status < 300) {
    logger.info(`Webhook sent successfully: ${response.status}`);
  } else {
    logger.warn(`Webhook responded with non-2xx status: ${response.status}`, response.data);
  }

  return {
    status: response.status,
    data: response.data
  };
}

async function notifyBackend(url, secret, payload) {
  if (!url) {
    logger.info('BACKEND_INTERNAL_URL not set, skipping backend notification');
    return { skipped: true };
  }

  const response = await axios.post(url, payload, {
    headers: {
      'Content-Type': 'application/json',
      'X-Parser-Secret': secret || ''
    },
    timeout: 10000,
    validateStatus: () => true
  });

  if (response.status >= 200 && response.status < 300) {
    logger.info(`Backend notification sent successfully: ${response.status}`);
  } else {
    logger.warn(`Backend notification responded with non-2xx status: ${response.status}`, response.data);
  }

  return {
    status: response.status,
    data: response.data
  };
}

module.exports = {
  sendWebhook,
  notifyBackend
};
