const { db } = require("../config/database");
const {
  create,
  getmeta,
  user,
  getUserByUserEmail,
  contact,
  checkIfEmailExists,
  addNewSubscriber,
  sandWelcomeEmail,
  saleForceLeadResponse,
} = require("./service");
const { genSaltSync, hashSync, compareSync } = require("bcrypt");
const { sign } = require("jsonwebtoken");
const path = require("path");
const fs = require("fs");
const validator = require("../auth/validator");
const axios = require("axios");
const qs = require("qs");
const { v4: uuidv4 } = require("uuid");

const getSalesForceToken = async () => {
  try {
    const loginCredentials = {
      username: "prasad.alamwar12@exceller.tech",
      password: "ftv@2024",
      grant_type: "password",
      client_id: "3MVG9fe4g9fhX0E6RdJnzZKI6hs5GMJ_0Ru7ndNbbTCYnMimHCsBLHaPuy2WZYhpcTa3MzChPzDzxAitBZ9Dg",
      client_secret: "23FAB0B5F2E7D78E64368CB9ED62DD10722BAD1409D535A5A87D31A96A2CD855",
    };
    const loginConfig = {
      method: "post",
      maxBodyLength: Infinity,
      url: "https://login.salesforce.com/services/oauth2/token",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      data: qs.stringify(loginCredentials),
    };

    const loginResponse = await axios.request(loginConfig);

    const authToken = loginResponse.data.access_token;
    const instanceUrl = loginResponse.data.instance_url;

    if (!authToken || !instanceUrl) {
      throw new Error("Invalid Salesforce login response");
    }

    return authToken;
  } catch (error) {
    throw error;
  }
};

const postLeadToSalesForce = async (token, formData) => {
  try {
    const salesForceConfig = {
      method: "post",
      maxBodyLength: Infinity,
      url: "https://momentum-inspiration-2218.my.salesforce.com/services/apexrest/CreateLead/",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      data: formData,
    };
    const saleforceResponse = await axios.request(salesForceConfig);
    return saleforceResponse;
  } catch (error) {
    throw error;
  }
};

module.exports = {
  createUser: (req, res) => {
    const body = req.body;
    const salt = genSaltSync(10);
    body.password = hashSync(body.password, salt);
    user(body, (err, results) => {
      if (err) {
        console.log(err);
        return res.status(500).json({
          status: "error",
          message: "Database connection error !!",
        });
      }
      return res.status(200).json({
        status: "success",
        data: results,
      });
    });
  },

//   createEnquiry: [
//     validator.validateEnquiry,
//     async (req, res) => {
//       const body = req.body;
//       const uniqueId = "FTV" + uuidv4().replace(/-/g, "").substring(0, 5);
//       create({ ...body, uniqueId }, async (err, results) => {
//         if (err) {
//           if (err.message === "Database query error") {
//             console.error("Database query error: ", err);
//             return res.status(500).json({
//               status: "error",
//               message: "Database query error !!",
//             });
//           } else if (
//             err.message ===
//               "User with this contact number already exists. Please use a different number." ||
//             err.message ===
//               "Duplicate entry. User with this unique code already exists."
//           ) {
//             return res.status(400).json({
//               status: "error",
//               message: err.message,
//             });
//           } else {
//             console.error("Error : ", err);
//             return res.status(500).json({
//               status: "error",
//               message: "Internal Server Error",
//             });
//           }
//         }

//         if (results.affectedRows > 0) {
//           try {
//             const token = await getSalesForceToken();

//             const {
//               fullname,
//               email,
//               contact,
//               state,
//               city,
//               investment,
//               message,
//             } = req.body;
//             const leadDataSalesForce = {
//               req: {
//                 Name: fullname || "No Data",
//                 email: email || "No Data",
//                 mobile: contact || "No Data",
//                 LeadIdentifier: "Web",
//                 product: "Beauty&Wellness",
//                 subProduct: "Nail STUDIO",
//                 investment: investment || "No Data",
//                 campaignCode: "",
//                 occupation: "No Data",
//                 city: city || "No Data",
//                 remarks:
//                   "state : " +
//                     state +
//                     "City : " +
//                     city  + "message : " + message,
//               },
//             };

//             const saleforceResponse = await postLeadToSalesForce(
//               token,
//               leadDataSalesForce
//             );
//             // console.log("Here is saleforce Data response " + saleforceResponse);
//             if (err) {
//               return res.status(500).json({
//                 status: "error",
//                 message: "Database connection error !!",
//               });
//             }
//             saleForceLeadResponse(
//               { ...saleforceResponse.data, uniqueId },
//               (err, results) => {
//                 if (err) {
//                   return res.status(500).json({
//                     status: "error",
//                     message: "Error While Inserting Response !!",
//                   });
//                 }
//                 return res.status(200).json({
//                   status: "success",
//                   data: {
//                     results: results,
//                     salesforceData: saleforceResponse.data,
//                   },
//                 });
//               }
//             );
//           } catch (error) {
//             return res.status(500).json({
//               status: "error",
//               message: "Error occurred while Posting Data in Salesforce API",
//             });
//           }
//         } else {
//           return res.status(200).json({
//             status: "success",
//             data: results,
//           });
//         }
//       });
//     },
//   ],

createEnquiry: [
  validator.validateEnquiry,
  async (req, res) => {
    const body = req.body;
    const uniqueId = "FTV" + uuidv4().replace(/-/g, "").substring(0, 5);

    create({ ...body, uniqueId }, async (err, results) => {
      if (err) {
        if (err.message === "Database query error") {
          console.error("Database query error: ", err);
          return res.status(500).json({
            status: "error",
            message: "Database query error !!",
          });
        } else if (
          err.message ===
            "User with this contact number already exists. Please use a different number." ||
          err.message ===
            "Duplicate entry. User with this unique code already exists."
        ) {
          return res.status(400).json({
            status: "error",
            message: err.message,
          });
        } else {
          console.error("Error : ", err);
          return res.status(500).json({
            status: "error",
            message: "Internal Server Error",
          });
        }
      }

      // Handle successful insertion into database
      return res.status(200).json({
        status: "success",
        data: results,
      });
    });
  },
],

  contactus: [
    validator.validateContact,
    (req, res) => {
      const body = req.body;
      contact(body, (err, results) => {
        if (err) {
          return res.status(500).json({
            status: "error",
            message: "Database connection error !!",
          });
        }
        return res.status(200).json({
          status: "success",
          data: results,
        });
      });
    },
  ],

  getmeta: (req, res) => {
    const { metasource } = req.params;
    if (!metasource) {
      return res.status(400).json({
        status: "error",
        message: "Meta source not provided in the query parameter",
      });
    }

    getmeta(metasource, (err, results) => {
      if (err) {
        console.log(err);
        return res.status(500).json({
          status: "error",
          message: "Database connection error !!",
        });
      }

      if (!results || results.length === 0) {
        return res.status(404).json({
          status: "error",
          message: "No meta information found for the provided source",
        });
      }

      return res.status(200).json({
        status: "success",
        data: results,
      });
    });
  },

  login: (req, res) => {
    const body = req.body;
    getUserByUserEmail(body.email, (err, results) => {
      if (err) {
        console.log(err);
      }
      if (!results) {
        return res.json({
          status: false,
          data: "invalid email or password !",
        });
      }
      const result = compareSync(body.password, results.password);
      if (result) {
        results.password = undefined;
        const jsontoken = sign({ result: results }, "qwe1234", {
          expiresIn: "24h",
        });
        return res.json({
          status: true,
          message: "Login Successfully !",
          token: jsontoken,
        });
      } else {
        return res.json({
          status: false,
          data: "invalid email or password !",
        });
      }
    });
  },

  subscribe: (req, res) => {
    const subscribe_email = req.params.email;
    // console.log(subscribe_email);

    if (!subscribe_email) {
      return res.status(404).json({
        status: "error",
        message: "Email not provided in the query parameter",
      });
    }

    checkIfEmailExists(subscribe_email, (err, results) => {
      if (err) {
        return res.status(500).json({
          status: "error",
          message: "Database Connection Error !!",
        });
      }
      // console.log(results);

      if (results.length > 0) {
        return res.status(200).json({
          status: "success",
          message: "User already subscribed",
        });
      } else {
        const subscribeData = {
          email: subscribe_email,
          subscribe_status: 0,
          created_at: new Date(),
        };
        addNewSubscriber(subscribeData, (err, results) => {
          if (err) {
            return res.status(400).json({
              status: "error",
              message: "Error while adding subscriber to the database",
            });
          }
          sandWelcomeEmail(subscribe_email, (err, emailSent) => {
            if (err) {
              return res.status(500).json({
                status: "error",
                message: "Error while sending welcome email",
              });
            }

            return res.status(201).json({
              status: "success",
              message: "Subscribed successfully. Welcome email sent!",
            });
          });
        });
      }
    });
  },
};
