var jwt = require("jsonwebtoken");
const { config } = require("dotenv");
const { Setting } = require("../models");
const axios = require("axios");
config();
const env = process.env.ENV;
const envCredential = require("../config");
const NOTIFICATION_TOKEN = envCredential.NOTIFICATION_TOKEN;

const getReqInformation = (req) => {
  const protocol = env == "dev" ? "http" : "https";
  const currentUrl = protocol + "://" + req.get("host") + req.originalUrl;
  let endpointArr = req.originalUrl?.split("/");
  let endpoint = endpointArr[endpointArr.length - 1].split("?")[0];
  const baseUrl = protocol + "://" + req.get("host");
  return {
    endPoint: endpoint,
    fullUrl: currentUrl,
    baseUrl: baseUrl,
  };
};

const generateToken = async (data) => {
  const accessToken = jwt.sign(
    {
      id: data.id,
    },
    data.SECRET_KEY
  );

  return accessToken;
};

const getSettings = async () => {
  let settings = await Setting.findAll({
    raw: true,
  });
  let finalSettings = {};
  settings.map((e) => {
    finalSettings[e.key] = e.value;
  });

  return finalSettings;
};

const generateCode = () => {
  return (
    Math.random().toString(36).slice(2) +
    "" +
    Math.random().toString(36).slice(2)
  );
};

const generateOTP = () => {
  // return Math.floor(1000 + Math.random() * 9000); // Ensures a 4-digit number
  return 1234;
};

const generateOrderId = () => {
  return (
    "ORDER_" +
    Date.now() +
    "_" +
    Math.random().toString(36).substring(7).toUpperCase()
  );
};

// topic = /topics/topic_notification
const sendNotificationToAllUsers = async (data, topic) => {
  try {
    let message = {
      notification: {
        title: data.title,
        body: data.body,
      },
      topic: topic,
    };
    const res = await admin.messaging().send(message);
    console.log("Notification sent successfully");
    return true;
  } catch (err) {
    console.log(err);
    throw new Error(err);
  }
};

const sendNotificationToUser = async (tokens, data) => {
  try {
    let message = {
      notification: {
        title: data.title,
        body: data.body,
      },
      tokens: tokens,
    };
    const res = await admin.messaging().sendEachForMulticast(message);
    console.log("Notification sent successfully");
    return true;
  } catch (err) {
    console.log(err);
    throw new Error(err);
  }
};

module.exports = {
  getReqInformation,
  generateToken,
  getSettings,
  generateCode,
  generateOrderId,
  sendNotificationToAllUsers,
  sendNotificationToUser,
  generateOTP,
};
