'use strict';
const crypto = require('crypto');
const { getSetting } = require('../db');

function payfastParams(order, items) {
  const sandbox = getSetting('payfast_sandbox', '1') === '1';
  const base = sandbox ? 'https://sandbox.payfast.co.za' : 'https://www.payfast.co.za';
  const email = getSetting('email', 'wasup1606@gmail.com');

  const itemNames = items.map((i) => `${i.name} x${i.qty}`).slice(0, 9).join(', ');

  const pf = {
    merchant_id: getSetting('payfast_merchant_id', ''),
    merchant_key: getSetting('payfast_merchant_key', ''),
    return_url: `${getSetting('site_url', '')}/order/${order.order_number}?payfast=success`,
    cancel_url: `${getSetting('site_url', '')}/checkout?payfast=cancelled`,
    notify_url: `${getSetting('site_url', '')}/payfast/notify`,
    m_payment_id: order.order_number,
    amount: order.total.toFixed(2),
    item_name: itemNames || 'TOUS CINO order',
    email_address: order.email || email,
    custom_str1: String(order.user_id || ''),
    name_first: (order.name || '').split(' ')[0] || 'Customer',
    name_last: (order.name || '').split(' ').slice(1).join(' ') || 'TOUS CINO',
    cell_number: (order.phone || '').replace(/\D/g, ''),
    address_line_1: order.address_line1 || '',
    address_line_2: order.address_line2 || '',
    address_city: order.city || '',
    address_state: order.province || '',
    address_postalcode: order.postal_code || '',
    address_country: 'ZAF',
  };

  const passphrase = getSetting('payfast_passphrase', '');
  const pfOutput = { ...pf };
  delete pfOutput.signature;
  let paramString = Object.keys(pfOutput)
    .sort()
    .map((k) => `${k}=${encodeURIComponent(String(pfOutput[k]).trim()).replace(/%20/g, '+')}`)
    .join('&');
  if (passphrase) paramString += `&passphrase=${encodeURIComponent(passphrase.trim()).replace(/%20/g, '+')}`;
  pf.signature = crypto.createHash('md5').update(paramString).digest('hex');

  return { base, pf, action: `${base}/eng/process` };
}

function verifyPayfastSignature(body) {
  const passphrase = getSetting('payfast_passphrase', '');
  const signature = body.signature;
  const clone = { ...body };
  delete clone.signature;
  let paramString = Object.keys(clone)
    .sort()
    .map((k) => `${k}=${encodeURIComponent(String(clone[k]).trim()).replace(/%20/g, '+')}`)
    .join('&');
  if (passphrase) paramString += `&passphrase=${encodeURIComponent(passphrase.trim()).replace(/%20/g, '+')}`;
  const check = crypto.createHash('md5').update(paramString).digest('hex');
  return check === signature;
}

module.exports = { payfastParams, verifyPayfastSignature };
