const db = require("../config/db"); // Assuming you have set up the database connection
const jwt = require("jsonwebtoken");
const axios = require("axios"); // Import axios for making HTTP requests
const fs = require('fs');
const path = require('path');


const getScripts = async (req, res) => {
    
    const { fields='' } = req.query; // Extract user_id from query parameters

  try {
      
    // Access the Authorization token from the request headers
    const authHeader = req.headers['authorization']; // Get the 'Authorization' header
    if (!authHeader) {
      return res.status(401).json({ message: "Unauthorized Access" });
    }
    const accessToken = authHeader.split(' ')[1];  //Extract the token (it will be in the form "Bearer <token>")
    const decodedData = jwt.verify(accessToken, process.env.JWT_SECRET_KEY); // Verify and decode the token
    const user_id = decodedData.user_id; // Assuming 'user_id' is stored in the payload of the token 
    
    // Define allowed fields to prevent SQL injection
    const allowedFields = ["id", "script_name", "script_name", "script_placement", "script", "is_global", "on_off"]; // Add only valid column names
    let selectedFields = "*";
    
    if (fields) {
      const requestedFields = fields.split(",").map((field) => field.trim());
      const validFields = requestedFields.filter((field) => allowedFields.includes(field));

      if (validFields.length > 0) {
        selectedFields = validFields.join(",");
      }
    }
    
    // Query to fetch scripts
    const query = `SELECT ${selectedFields} FROM event_scripts WHERE user_id = ?`;
    
    
    
    // Execute the query
    const [event_scripts] = await db.query(query, [user_id]);

    // If no results found, return a message
    if (event_scripts.length === 0) {
      return res.status(404).json({ message: "No scripts found for the given user." });
    }

    // Return the structured data
    res.status(200).json(event_scripts);
  } catch (error) {
    res.status(500).json({
      message: "An error occurred while fetching the scripts",
      error: error.message,
    });
  }
};

const getScriptsPerIds = async (req, res) => {
  const { script_ids } = req.query; // Extract user_id and script_ids from query parameters

  if (!script_ids) {
    return res.status(400).json({ message: "Script IDs are required" });
  }

  try {
    // Split the comma-separated script_ids into an array of integers
    const scriptIdsArray = script_ids.split(',').map(id => parseInt(id.trim()));

    // Define the query to get the scripts for the given user_id and script_ids
    const query = `
      SELECT * FROM event_scripts
      WHERE id IN (?)`;
    
    // Execute the query with the user_id and the array of script_ids
    const [event_scripts] = await db.query(query, [scriptIdsArray]);

    // If no scripts are found, return a message
    if (event_scripts.length === 0) {
      return res.status(404).json({ message: "No scripts found for the given user and script IDs." });
    }

    // Return the structured data
    res.status(200).json(event_scripts);
  } catch (error) {
    res.status(500).json({
      message: "An error occurred while fetching the scripts",
      error: error.message,
    });
  }
};


// Controller to add a new script
const addScript = async (req, res) => {
  const { script_name, script_placement="Header", script, is_global="no", on_off="off" } = req.body;

  if (!script_name || !script) {
    return res.status(400).json({ message: "script Name, script and user are required!" });
  }

  try {
    
    // Access the Authorization token from the request headers
    const authHeader = req.headers['authorization']; // Get the 'Authorization' header
    if (!authHeader) {
      return res.status(401).json({ message: "Unauthorized Access" });
    }
    const accessToken = authHeader.split(' ')[1];  //Extract the token (it will be in the form "Bearer <token>")
    const decodedData = jwt.verify(accessToken, process.env.JWT_SECRET_KEY); // Verify and decode the token
    const user_id = decodedData.user_id; // Assuming 'user_id' is stored in the payload of the token   
      
    const query = `INSERT INTO event_scripts (user_id, script_name, script_placement, script, is_global, on_off) 
                   VALUES (?, ?, ?, ?, ?, ?)`;

    await db.query(query, [user_id, script_name, script_placement, script, is_global, on_off]);

    res.status(201).json({ message: "Script added successfully" });
  } catch (error) {
    res
      .status(500)
      .json({ message: "An error occurred while adding the script", error });
  }
};


// Controller to update an existing script
const updateScript = async (req, res) => {
  const { script_name, script_placement = "Header", script, is_global = "no", on_off = "off" } = req.body;
  const { id } = req.params; // Get the playlist id from the URL params

  if (!script_name || !script) {
    return res.status(400).json({ message: "script Name, script and user are required!" });
  }

  try {
      
    // Access the Authorization token from the request headers
    const authHeader = req.headers['authorization']; // Get the 'Authorization' header
    if (!authHeader) {
      return res.status(401).json({ message: "Unauthorized Access" });
    }
    const accessToken = authHeader.split(' ')[1];  //Extract the token (it will be in the form "Bearer <token>")
    const decodedData = jwt.verify(accessToken, process.env.JWT_SECRET_KEY); // Verify and decode the token
    const user_id = decodedData.user_id; // Assuming 'user_id' is stored in the payload of the token   
    
    // Check user authentication to perform action - start
    const [userCheck] = await db.query("SELECT role FROM users WHERE id = ? LIMIT 1", [user_id]);
    if (userCheck.length === 0) {
      return res.status(404).json({ message: "User not found" });
    }
    
    const userRole = userCheck[0].role;
    
    if (userRole != 'super_admin') {
        
    // Fetch the event from the DB using eventId to get event_hash_id
    const checkExistenceQuery = 'SELECT id FROM event_scripts WHERE id = ? AND user_id = ? LIMIT 1';
    const [checkExistenceResult] = await db.query(checkExistenceQuery, [id,user_id]);

    // Check if the event exists
    if (checkExistenceResult.length === 0) {
      return res.status(404).json({ message: "Script not found or you are not authorize to take this action" });
    }    
        
    }
    // Check user authentication to perform action - start    
      
      
    // Ensure the script exists before updating
    const checkQuery = `SELECT script_name FROM event_scripts WHERE id = ?`;
    const [existingScript] = await db.query(checkQuery, [id]);

    if (existingScript.length === 0) {
      return res.status(404).json({ message: "Script not found for the provided user and script name!" });
    }

    const updateQuery = `UPDATE event_scripts SET 
                          script_name = ?,
                          script_placement = ?,
                          script = ?, 
                          is_global = ? 
                          WHERE id = ?`;

    await db.query(updateQuery, [script_name, script_placement, script, is_global, id]);

    res.status(200).json({ message: "Script updated successfully" });
  } catch (error) {
    res.status(500).json({ message: "An error occurred while updating the script", error: error.message });
  }
};


// Controller to update the on_off status of an existing script
const updateScriptOnOff = async (req, res) => {
  const { on_off } = req.body; // Get the on_off status from the request body
  const { id } = req.params; // Get the script id from the URL params

  if (!on_off) {
    return res.status(400).json({ message: "on_off status is required" });
  }

  if (on_off !== "on" && on_off !== "off") {
    return res.status(400).json({ message: "on_off status must be either 'on' or 'off'" });
  }

  try {
      
    // Access the Authorization token from the request headers
    const authHeader = req.headers['authorization']; // Get the 'Authorization' header
    if (!authHeader) {
      return res.status(401).json({ message: "Unauthorized Access" });
    }
    const accessToken = authHeader.split(' ')[1];  //Extract the token (it will be in the form "Bearer <token>")
    const decodedData = jwt.verify(accessToken, process.env.JWT_SECRET_KEY); // Verify and decode the token
    const user_id = decodedData.user_id; // Assuming 'user_id' is stored in the payload of the token  
    
    // Check user authentication to perform action - start
    const [userCheck] = await db.query("SELECT role FROM users WHERE id = ? LIMIT 1", [user_id]);
    if (userCheck.length === 0) {
      return res.status(404).json({ message: "User not found" });
    }
    
    const userRole = userCheck[0].role;
    
    if (userRole != 'super_admin') {
        
    // Fetch the event from the DB using eventId to get event_hash_id
    const checkExistenceQuery = 'SELECT id FROM event_scripts WHERE id = ? AND user_id = ? LIMIT 1';
    const [checkExistenceResult] = await db.query(checkExistenceQuery, [id,user_id]);

    // Check if the event exists
    if (checkExistenceResult.length === 0) {
      return res.status(404).json({ message: "Script not found or you are not authorize to take this action" });
    }    
        
    }
    // Check user authentication to perform action - start    
      
    // Ensure the script exists before updating
    const checkQuery = `SELECT id FROM event_scripts WHERE id = ? LIMIT 1`;
    const [existingScript] = await db.query(checkQuery, [id]);

    if (existingScript.length === 0) {
      return res.status(404).json({ message: "Script not found for the provided ID!" });
    }

    // Update the on_off status of the script
    const updateQuery = `UPDATE event_scripts SET on_off = ? WHERE id = ?`;
    await db.query(updateQuery, [on_off, id]);

    res.status(200).json({ message: `Script on_off status updated to ${on_off} successfully` });
  } catch (error) {
    res.status(500).json({
      message: "An error occurred while updating the on_off status",
      error: error.message,
    });
  }
};


// Controller to delete an existing script by its ID
const deleteScript = async (req, res) => {
  const { id } = req.params; // Get the script id from the URL params

  if (!id) {
    return res.status(400).json({ message: "Script ID is required" });
  }

  try {
      
    // Access the Authorization token from the request headers
    const authHeader = req.headers['authorization']; // Get the 'Authorization' header
    if (!authHeader) {
      return res.status(401).json({ message: "Unauthorized Access" });
    }
    const accessToken = authHeader.split(' ')[1];  //Extract the token (it will be in the form "Bearer <token>")
    const decodedData = jwt.verify(accessToken, process.env.JWT_SECRET_KEY); // Verify and decode the token
    const user_id = decodedData.user_id; // Assuming 'user_id' is stored in the payload of the token   
      
    // Check user authentication to perform action - start
    const [userCheck] = await db.query("SELECT role FROM users WHERE id = ? LIMIT 1", [user_id]);
    if (userCheck.length === 0) {
      return res.status(404).json({ message: "User not found" });
    }
    
    const userRole = userCheck[0].role;
    
    if (userRole != 'super_admin') {
        
    // Fetch the event from the DB using eventId to get event_hash_id
    const checkExistenceQuery = 'SELECT id FROM event_scripts WHERE id = ? AND user_id = ? LIMIT 1';
    const [checkExistenceResult] = await db.query(checkExistenceQuery, [id,user_id]);

    // Check if the event exists
    if (checkExistenceResult.length === 0) {
      return res.status(404).json({ message: "Script not found or you are not authorize to take this action" });
    }    
        
    }
    // Check user authentication to perform action - start   
      
    // Ensure the script exists before attempting to delete
    const checkQuery = `SELECT * FROM event_scripts WHERE id = ?`;
    const [existingScript] = await db.query(checkQuery, [id]);

    if (existingScript.length === 0) {
      return res.status(404).json({ message: "Script not found for the provided ID!" });
    }

    // Delete the script from the database
    const deleteQuery = `DELETE FROM event_scripts WHERE id = ?`;
    await db.query(deleteQuery, [id]);

    res.status(200).json({ message: "Script deleted successfully" });
  } catch (error) {
    res.status(500).json({
      message: "An error occurred while deleting the script",
      error: error.message,
    });
  }
};


module.exports = { getScripts, getScriptsPerIds, addScript, updateScript, updateScriptOnOff, deleteScript};
