import { env } from '../config/env';

/**
 * SMS (Sprint 5, TEPL), for emergency alerts only: the one channel that
 * reaches a phone with no data. The gateway is TEPL's choice, so this posts
 * { to, text } to whatever HTTP endpoint is configured; until then messages
 * are logged, like WhatsApp in dry-run.
 */

export interface SmsResult {
  sent: boolean;
  mode: 'log' | 'webhook' | 'error';
}

export function isSmsConfigured() {
  return env.SMS_PROVIDER === 'webhook' && !!env.SMS_WEBHOOK_URL;
}

/** Digits with the country code: a 10-digit Indian number gets 91. */
const smsPhone = (phone: string) => {
  const d = phone.replace(/\D/g, '');
  return d.length === 10 ? `91${d}` : d;
};

export async function sendSms(phone: string, text: string): Promise<SmsResult> {
  if (!isSmsConfigured()) {
    // eslint-disable-next-line no-console
    console.log(`[sms:log] → ${phone}: ${text}`);
    return { sent: false, mode: 'log' };
  }
  try {
    const res = await fetch(env.SMS_WEBHOOK_URL!, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', ...(env.SMS_WEBHOOK_TOKEN ? { Authorization: `Bearer ${env.SMS_WEBHOOK_TOKEN}` } : {}) },
      body: JSON.stringify({ to: smsPhone(phone), text: text.slice(0, 480) }),
      signal: AbortSignal.timeout(10_000),
    });
    return { sent: res.ok, mode: res.ok ? 'webhook' : 'error' };
  } catch {
    return { sent: false, mode: 'error' };
  }
}
