const AdminAuthorizationToken = require("../../models/AdminAuthorizationToken");

function generateRandomString(length) {
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  const charactersLength = characters.length;

  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}
exports.generateRandomToken = async (req, res, next) => {
  try {
    const { admin_user_id, request_only = "false" } = req.query;

    if (!admin_user_id)
      return res
        .status(200)
        .json({ success: false, message: "Invalid Admin User ID" });
    const randomString = generateRandomString(50);
    await AdminAuthorizationToken.create({
      admin_user_id,
      token: randomString,
      request_only: request_only === "true",
    });

    res.status(200).json({ success: true, token: randomString });
  } catch (err) {
    next(err);
  }
};

exports.verifyAdminToken = async (req, res, next) => {
  try {
    const { token } = req.body;

    if (!token) return res.status(400).json({ success: false });

    const validToken = await AdminAuthorizationToken.findOne({
      where: {
        token,
      },
    });

    if (!validToken) return res.status(400).json({ success: false });

    res
      .status(200)
      .json({
        success: true,
        token,
        admin_user_id: validToken.admin_user_id,
        requestOnly: validToken.request_only,
      });
  } catch (err) {
    next(err);
  }
};
