import { servicesConfig } from "$config/index.js";
import { smsClient } from "$clients/index.js";

const PERSIAN_DIGITS = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];

const toPersianDigits = (value) =>
  String(value ?? "").replace(/\d/g, (digit) => PERSIAN_DIGITS[Number(digit)]);

const normalizeIpAddress = (value = "") => {
  if (!value) {
    return null;
  }

  const firstValue = String(value).split(",")[0].trim();

  if (!firstValue) {
    return null;
  }

  if (firstValue === "::1") {
    return "127.0.0.1";
  }

  if (firstValue.startsWith("::ffff:")) {
    return firstValue.replace("::ffff:", "");
  }

  return firstValue;
};

export const sendOTPSms = async (config) => {
  const templateId = servicesConfig.smsConfig.otpTemplateId;

  const mobile = config.mobile || null;
  const message = config.message || null;

  try {
    const response = await smsClient.post("/send/verify", {
      Mobile: mobile,
      TemplateId: templateId,
      Parameters: [
        {
          Name: "CODE",
          Value: message,
        },
      ],
    });
    return response.data;
  } catch (error) {
    throw error;
  }
};

export const sendLoginNotifSms = async (config) => {
  const templateId = servicesConfig.smsConfig.loginNotifTemplateId;

  const mobile = config.mobile ? toPersianDigits(config.mobile) : null;
  const fullName = config.fullName || "";
  const date = new Date().toLocaleDateString("fa-IR") || null;
  const time = new Date().toLocaleTimeString("fa-IR") || null;

  try {
    const response = await smsClient.post("/send/verify", {
      Mobile: mobile,
      TemplateId: templateId,
      Parameters: [
        {
          Name: "FULLNAME",
          Value: fullName,
        },
        {
          Name: "DATE",
          Value: date,
        },
        {
          Name: "TIME",
          Value: time,
        },
      ],
    });
    return response.data;
  } catch (error) {
    throw error;
  }
};
