import pg from 'pg';

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

async function syncWebgains() {
  const apiUrl = 'https://api.webgains.com/2.0';
  const clientId = process.env.WEBGAINS_CLIENT_ID;
  const clientSecret = process.env.WEBGAINS_CLIENT_SECRET;

  if (!clientId || !clientSecret) {
    console.log('Webgains credentials not configured, skipping');
    return;
  }

  // Get OAuth token
  const tokenRes = await fetch('https://api.webgains.com/2.0/oauth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: `grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}`,
  });
  const { access_token } = await tokenRes.json();

  // Fetch transactions from last 48h
  const since = new Date(Date.now() - 48 * 3600 * 1000).toISOString();
  const res = await fetch(`${apiUrl}/reporting/transactions?dateFrom=${since}&dateType=transaction`, {
    headers: { Authorization: `Bearer ${access_token}` },
  });
  const transactions = await res.json();

  for (const tx of (Array.isArray(transactions) ? transactions : [])) {
    const clickRef = tx.clickRef || null;
    const status = tx.status === 'confirmed' ? 'approved' : tx.status === 'rejected' ? 'rejected' : 'pending';

    await pool.query(`
      INSERT INTO conversions (click_ref, network, network_id, status, commission, sale_amount, conversion_time, network_data, matched)
      VALUES ($1, 'webgains', $2, $3, $4, $5, $6, $7, $8)
      ON CONFLICT (network, network_id) DO UPDATE SET status = $3, commission = $4, updated_at = now()
    `, [clickRef, tx.transactionId, status, tx.commission, tx.saleValue, tx.transactionDate, JSON.stringify(tx), !!clickRef]);

    if (clickRef) {
      const click = await pool.query('SELECT product_id, shop_id, created_at FROM click_events WHERE click_ref = $1 LIMIT 1', [clickRef]);
      if (click.rows.length) {
        await pool.query(`
          UPDATE conversions SET product_id = $1, shop_id = $2, click_time = $3, matched = true
          WHERE network = 'webgains' AND network_id = $4
        `, [click.rows[0].product_id, click.rows[0].shop_id, click.rows[0].created_at, tx.transactionId]);
      }
    }
  }
  console.log(`Webgains: processed ${Array.isArray(transactions) ? transactions.length : 0} transactions`);
}

async function syncAwin() {
  const apiKey = process.env.AWIN_API_TOKEN || process.env.AWIN_API_KEY;
  const publisherId = process.env.AWIN_PUBLISHER_ID;

  if (!apiKey || !publisherId) {
    console.log('Awin credentials not fully configured (need AWIN_API_TOKEN + AWIN_PUBLISHER_ID), skipping');
    return;
  }

  const endDate = new Date().toISOString().slice(0, 10) + 'T23:59:59';
  const startDate = new Date(Date.now() - 48 * 3600 * 1000).toISOString().slice(0, 10) + 'T00:00:00';

  const res = await fetch(
    `https://api.awin.com/publishers/${publisherId}/transactions/?startDate=${startDate}&endDate=${endDate}&timezone=Europe/Amsterdam`,
    { headers: { Authorization: `Bearer ${apiKey}` } }
  );

  if (!res.ok) {
    console.error(`Awin API error: ${res.status} ${await res.text()}`);
    return;
  }

  const transactions = await res.json();
  let count = 0;

  for (const tx of (Array.isArray(transactions) ? transactions : [])) {
    const clickRef = tx.clickRef || null;
    const status = tx.commissionStatus === 'approved' ? 'approved' : tx.commissionStatus === 'declined' ? 'rejected' : 'pending';
    const commission = tx.commissionAmount?.amount || 0;
    const saleAmount = tx.saleAmount?.amount || 0;
    const conversionTime = tx.transactionDate || new Date().toISOString();

    await pool.query(`
      INSERT INTO conversions (click_ref, network, network_id, status, commission, sale_amount, conversion_time, network_data, matched)
      VALUES ($1, 'awin', $2, $3, $4, $5, $6, $7, $8)
      ON CONFLICT (network, network_id) DO UPDATE SET status = $3, commission = $4, updated_at = now()
    `, [clickRef, String(tx.id), status, commission, saleAmount, conversionTime, JSON.stringify(tx), !!clickRef]);

    if (clickRef) {
      const click = await pool.query('SELECT product_id, shop_id, created_at FROM click_events WHERE click_ref = $1 LIMIT 1', [clickRef]);
      if (click.rows.length) {
        await pool.query(`
          UPDATE conversions SET product_id = $1, shop_id = $2, click_time = $3, matched = true
          WHERE network = 'awin' AND network_id = $4
        `, [click.rows[0].product_id, click.rows[0].shop_id, click.rows[0].created_at, String(tx.id)]);
      }
    }
    count++;
  }
  console.log(`Awin: processed ${count} transactions`);
}

async function syncTradeTracker() {
  const customerId = process.env.TT_CUSTOMER_ID;
  const passphrase = process.env.TT_PASSPHRASE;

  if (!customerId || !passphrase) {
    console.log('TradeTracker credentials not configured, skipping');
    return;
  }

  // TradeTracker API integration placeholder
  // In production, use their SOAP/REST API with the credentials
  console.log('TradeTracker sync: placeholder (configure API integration)');
}

async function main() {
  console.log(`[${new Date().toISOString()}] Starting revenue sync...`);

  const results = await Promise.allSettled([syncWebgains(), syncAwin(), syncTradeTracker()]);
  results.forEach((r, i) => {
    if (r.status === 'rejected') console.error(`Sync ${i} failed:`, r.reason);
  });

  console.log('Revenue sync complete.');
  await pool.end();
}

main().catch(err => { console.error(err); process.exit(1); });
