const fs = require('fs/promises');
const path = require('path');

const CRM_WEBHOOK_URL = process.env.CRM_WEBHOOK_URL || '';
const CRM_TOKEN = process.env.CRM_TOKEN || '';
const HELP_DESK_EMAIL = process.env.HELP_DESK_EMAIL || 'hello@leadsniper.com';
const LOG_FILE = path.join(__dirname, 'data', 'crm.log');

async function ensureLogDir() {
  await fs.mkdir(path.dirname(LOG_FILE), { recursive: true });
}

async function logFallback(entry) {
  await ensureLogDir();
  const line = `${new Date().toISOString()} ${JSON.stringify(entry)}\n`;
  await fs.appendFile(LOG_FILE, line, 'utf-8');
}

async function postToCrm(type, payload) {
  if (!CRM_WEBHOOK_URL) {
    await logFallback({ type, payload, note: 'CRM_WEBHOOK_URL missing – logged locally' });
    return;
  }
  const body = {
    type,
    payload,
    helpDesk: HELP_DESK_EMAIL,
  };
  const response = await fetch(CRM_WEBHOOK_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...(CRM_TOKEN ? { Authorization: `Bearer ${CRM_TOKEN}` } : {}),
    },
    body: JSON.stringify(body),
  });
  if (!response.ok) {
    throw new Error(`CRM request failed with status ${response.status}`);
  }
}

async function sendToCrm(type, payload) {
  try {
    await postToCrm(type, payload);
  } catch (error) {
    await logFallback({ type, payload, error: error.message });
  }
}

module.exports = {
  sendToCrm,
};
