const axios = require("axios");
require("dotenv").config(); // Load environment variables

// Helper to normalize Sri Lankan phone numbers (e.g., 077... to 9477...)
const normalizePhoneNumber = (raw) => {
  if (!raw) return null;
  let p = String(raw).trim().replace(/\s+/g, ""); // Remove spaces
  if (p.startsWith("+")) p = p.slice(1);
  if (p.startsWith("0")) p = p.slice(1);
  if (!p.startsWith("94")) p = "94" + p;
  return p;
};

/**
 * Sends an SMS using either development credentials or institution-specific settings.
 * @param {string} rawPhone - The raw phone number.
 * @param {string} message - The message to send.
 * @param {object|null} institutionSettings - The settings object for the institution, required in production.
 * @returns {Promise<object>} An object indicating success or failure.
 */
const sendSms = async (rawPhone, message, institutionSettings) => {
  let smsBaseUrl, smsSenderId, smsApiKey;
  const isProduction = process.env.NODE_ENV === "production";

  if (isProduction) {
    // --- PRODUCTION LOGIC ---
    // In production, we MUST use the settings passed from the controller.
    if (!institutionSettings || !institutionSettings.sms_api_key) {
      console.warn(
        `PRODUCTION: SMS sending skipped for institution ID ${institutionSettings?.institution_id} because SMS settings are not configured.`
      );
      return { ok: true, reason: "production_mode_no_credentials" };
    }
    smsBaseUrl = institutionSettings.sms_base_url;
    smsSenderId = institutionSettings.sms_sender_id;
    smsApiKey = institutionSettings.sms_api_key;
  } else {
    // --- DEVELOPMENT LOGIC ---
    // In development, we use the fallback credentials from the .env file.
    smsBaseUrl = process.env.DEV_SMS_BASE_URL;
    smsSenderId = process.env.DEV_SMS_SENDER_ID;
    smsApiKey = process.env.DEV_SMS_API_KEY;

    // If even dev credentials aren't set, just log to console.
    if (!smsBaseUrl || !smsSenderId || !smsApiKey) {
      console.warn("--- DEVELOPMENT SMS SIMULATION ---");
      console.warn(
        "SMS dev credentials not found in .env. Logging to console instead."
      );
      console.log(`To: ${rawPhone}`);
      console.log(`Message: ${message}`);
      console.warn("----------------------------------");
      return { ok: true, reason: "development_mode_no_credentials" };
    }
  }

  try {
    const phone = normalizePhoneNumber(rawPhone);
    if (!phone || !message) {
      console.error("SMS Error: Invalid phone number or message provided.");
      return { ok: false, reason: "invalid_arguments" };
    }

    // Construct the URL with encoded parameters for a GET request
    // This part remains the same as it's generic.
    const url = `${smsBaseUrl}?recipient=${encodeURIComponent(
      phone
    )}&sender_id=${encodeURIComponent(
      smsSenderId
    )}&message=${encodeURIComponent(message)}&api_token=${encodeURIComponent(
      smsApiKey
    )}`;

    const res = await axios.get(url, { timeout: 10000 }); // 10-second timeout

    // Check for success based on the API provider's response
    if (res.status === 200) {
      return { ok: true, status: res.status, data: res.data };
    } else {
      console.error(
        `SMS provider returned non-200 status for ${phone}:`,
        res.status,
        res.data
      );
      return { ok: false, status: res.status, data: res.data };
    }
  } catch (e) {
    // This catches network errors, timeouts, etc.
    console.error(`SMS send failed for ${rawPhone} (axios error):`, e.message);
    return { ok: false, error: e.message };
  }
};

module.exports = { sendSms };
