import axios from 'axios';
import { normalizeSmsPhone } from './phone.helper';
import { sanitizeSmsText } from './sms-text.helper';

export async function sendSms(
  phone: string | null | undefined,
  message: string
): Promise<boolean> {
  const url = process.env.SMS_URL?.trim();
  const username = process.env.SMS_USERNAME?.trim();
  const password = process.env.SMS_PASSWORD?.trim();
  const from = process.env.SMS_FROM?.trim();

  if (!url || !username || !password || !from) {
    console.error('SMS configuration missing. Set SMS_URL, SMS_USERNAME, SMS_PASSWORD, and SMS_FROM.');
    return false;
  }

  const to = normalizeSmsPhone(phone);
  const text = sanitizeSmsText(String(message || '').trim());

  if (!to || !text) {
    return false;
  }

  try {
    await axios.get(url, {
      params: {
        username,
        password,
        from,
        to,
        message: text,
      },
    });
    return true;
  } catch (error) {
    console.error('SMS send error:', error);
    return false;
  }
}
