/**
 * Send SMS via n8n webhook → Twilio.
 * n8n handles Twilio auth + logs to ERPNext automatically.
 *
 * @param {string} phone - Phone number (e.g. +15145551234)
 * @param {string} message - SMS body
 * @param {string} customer - Customer ID (e.g. C-LPB4 or C-10000000034941) — logged as Communication in ERPNext
 * @param {object} [opts] - Extra options
 * @param {string} [opts.reference_doctype] - Link to specific doctype (default: Customer)
 * @param {string} [opts.reference_name] - Link to specific record
 * @returns {Promise<{ok: boolean, message: string, sid?: string}>}
 */

const N8N_WEBHOOK_URL = 'https://n8n.gigafibre.ca/webhook/sms-send'

export async function sendTestSms (phone, message, customer, opts = {}) {
  const payload = { phone, message, customer }
  if (opts.reference_doctype) payload.reference_doctype = opts.reference_doctype
  if (opts.reference_name) payload.reference_name = opts.reference_name
  const res = await fetch(N8N_WEBHOOK_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  })
  if (!res.ok) {
    const err = await res.text().catch(() => 'Unknown error')
    throw new Error('SMS failed (' + res.status + '): ' + err)
  }
  const data = await res.json()
  if (data.ok === false) throw new Error(data.message || 'SMS send error')
  return data
}
