const fs = require("fs");
const path = require("path");
const { db } = require("../config/database");
const { compareSync, genSaltSync, hashSync } = require("bcrypt");
const { getUserByUserEmail, user, create, checkFetchMetaData, checkIfEmailExists, addNewSubscriber, sendWelcomeEmail } = require("../models/service");
const { sign } = require("jsonwebtoken");
const validator = require("../auth/validator");
const { v4: uuidv4 } = require("uuid");

const DATA_DIR = path.join(__dirname, "..", "data");

function sanitizeEmailForFolder(email) {
  if (!email || typeof email !== "string") return "unknown";
  // Replace @ with _ and remove any characters that aren't safe for folder names
  const safe = email.replace(/@/g, "_").replace(/[^a-zA-Z0-9._-]/g, "_");
  return safe || "unknown";
}

function getUserFolderPath(email) {
  const folderName = sanitizeEmailForFolder(email);
  return path.join(DATA_DIR, folderName);
}

function portfolioFilenameFromEmail(email) {
  return "portfolio.pdf";
}

function generateFilename(suffix) {
  return `${suffix}.pdf`;
}


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(
          `Something went wrong while Creating User Error Report: ${err}`
        );
        return res
          .status(500)
          .json({ status: false, message: "Database Connection Error !" });
      }
      return res.status(200).json({ status: true, data: results });
    });
  },

  login: (req, res) => {
    const body = req.body;
    getUserByUserEmail(body.email, (err, results) => {
      if (err) {
        console.log(`Error while fetching Request : ${err}`);
      }
      if (!results) {
        return res
          .status(401)
          .json({ status: false, message: "Invalid Email or Password !" });
      }

      const result = compareSync(body.password, results.password);
      if (result) {
        result.password = undefined;
        const jsontoken = sign({ result: results }, "qwe1234", {
          expiresIn: "24h",
        });
        return res
          .status(200)
          .json({
            status: true,
            message: "Login Successfully !",
            token: jsontoken,
          });
      } else {
        return res
          .status(403)
          .json({ status: false, message: "Invalid Email or Password !" });
      }
    });
  },

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

      // Ensure data folder exists
      try {
        if (!fs.existsSync(DATA_DIR)) {
          fs.mkdirSync(DATA_DIR, { recursive: true });
        }
      } catch (dirErr) {
        console.error("Error creating data directory:", dirErr);
        return res.status(500).json({
          status: false,
          message: "Failed to create data directory.",
        });
      }

      // Create user folder based on email
      const userFolderPath = getUserFolderPath(body.email);
      try {
        if (!fs.existsSync(userFolderPath)) {
          fs.mkdirSync(userFolderPath, { recursive: true });
        }
      } catch (folderErr) {
        console.error("Error creating user folder:", folderErr);
        return res.status(500).json({
          status: false,
          message: "Failed to create user folder.",
        });
      }

      // Save portfolio file (required) in user folder
      const portfolioFilename = portfolioFilenameFromEmail(body.email);
      const portfolioPath = path.join(userFolderPath, portfolioFilename);
      try {
        fs.writeFileSync(portfolioPath, req.files.portfolio[0].buffer);
      } catch (writeErr) {
        console.error("Error saving portfolio PDF:", writeErr);
        return res.status(500).json({
          status: false,
          message: "Failed to save portfolio file.",
        });
      }

      // Save age proof file (required) in user folder
      const ageProofFilename = generateFilename("age_proof");
      const ageProofPath = path.join(userFolderPath, ageProofFilename);
      try {
        fs.writeFileSync(ageProofPath, req.files.age_proof[0].buffer);
      } catch (writeErr) {
        console.error("Error saving age proof PDF:", writeErr);
        return res.status(500).json({
          status: false,
          message: "Failed to save age proof file.",
        });
      }

      // Save marriage certificate file (optional) in user folder
      let marriageCertificatePath = null;
      if (req.files.marriage_certificate && req.files.marriage_certificate[0]) {
        const marriageCertFilename = generateFilename("marriage_certificate");
        const marriageCertFilePath = path.join(userFolderPath, marriageCertFilename);
        try {
          fs.writeFileSync(marriageCertFilePath, req.files.marriage_certificate[0].buffer);
          const folderName = sanitizeEmailForFolder(body.email);
          marriageCertificatePath = path.join("data", folderName, marriageCertFilename);
        } catch (writeErr) {
          console.error("Error saving marriage certificate PDF:", writeErr);
          return res.status(500).json({
            status: false,
            message: "Failed to save marriage certificate file.",
          });
        }
      }

      // Prepare file paths for database (relative to project root)
      const folderName = sanitizeEmailForFolder(body.email);
      const payload = {
        ...body,
        uniqueID,
        portfolio: path.join("data", folderName, portfolioFilename),
        age_proof: path.join("data", folderName, ageProofFilename),
        created_at: body.created_at ? new Date(body.created_at) : new Date(),
      };

      // Add marriage certificate path only if provided
      if (marriageCertificatePath) {
        payload.marriage_certificate = marriageCertificatePath;
      }

      create(payload, async (err, results) => {
        if (err) {
          if (err.message === "Database query error") {
            console.error("Database Query Error:", err);
            return res.status(500).json({
              status: false,
              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: false,
                message: err.message,
            });
          } else {
            console.error("Error : ", err);
            return res.status(500).json({
                status: false,
                message: "Internal Server error !"
            });
          }
        }
        return res.status(200).json({
            status: 200,
            data:results
        })
      });
    },
  ],


  getmeta: (req, res) => {
    const { metasource } = req.params;

    if(!metasource) {
        return res.status(400).json({
            status: false,
            message: "Meta Source not provided in the query parameter !!",
        });
    }

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

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

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

  },


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

    if(!subscribe_email) {
      return res.status(404).json({
        status: false,
        message: "Email Not Provided in the query parameter !",
      });
    }

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

      if(results.length > 0) {
        return res.status(200).json({
          status: true,
          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: false,
              message : "Error while adding subscriber to the Database !",
            });
          }
          sendWelcomeEmail(subscribe_email, (err, emailSent) => {
            if(err) {
              return res.status(500).json({
                status: false,
                message: "Error While sending Welcome Email",
              });
            }
            return res.status(200).json({
              status: true,
              message: "Subscribed successfully . Welcome Email Sent !"
            });
          });
          
        });
      }

    });

  }




};



