const jwt = require("jsonwebtoken");
const multer = require("multer");
require("dotenv").config();
const userModel = require("../models/user");
const path = require("path");

const verifyUser = async (req, res, next) => {
    const bearerHeader = req.headers["authorization"];

    if (typeof bearerHeader !== "undefined") {
        const bearer = bearerHeader.split(" ")[1];
        req.token = bearer;
        jwt.verify(bearer, process.env.SECRET_KEY, async (error, authData) => {
            if (error) {
                console.log("Invalid Token :", error);
                return res.status(403).json({
                    msg: "Invalid Token !"
                })
            } else {
                let id = authData._id || authData.id;
                let userData = await userModel.findById(id).select("-password");
                req.user = userData;
                next();
            }
        })
    } else {
        return res.status(403).json({
            msg: "Token Not Found!"
        })
    }
};

const imagePath = path.join(__dirname, "../public/user/")
const documentPath = path.join(__dirname, "../public/license")

const userStorage = multer.diskStorage({
    destination: (req, file, cb) => {
        if (file.mimetype.startsWith("image/")) {
            cb(null, imagePath);
        } else if (file.mimetype === "application/pdf") {
            cb(null, documentPath);
        } else {
            cb(new Error("Invalid File Type!"), false);
        }
    },
    filename: (req, file, cb) => {
        cb(null, Date.now() + "-" + file.originalname)
    }
});

const userFileFilter = (req, file, cb) => {
    // profileImage: only images
    if (file.fieldname === "profileImage") {
        if (file.mimetype.startsWith("image/")) return cb(null, true);
        return cb(new Error("Profile image must be an image"), false);
    }

    // portfolio: images OR PDFs
    if (file.fieldname === "portfolio") {
        if (file.mimetype.startsWith("image/") || file.mimetype === "application/pdf")
            return cb(null, true);
        return cb(new Error("Portfolio must be images or PDFs"), false);
    }

    // license: only PDFs
    if (file.fieldname === "license") {
        if (file.mimetype === "application/pdf") return cb(null, true);
        return cb(new Error("License must be PDF"), false);
    }

    // default catch
    cb(new Error("Invalid field"), false);
};

// One uploader for all fields
const userUpload = multer({
    storage: userStorage,
    fileFilter: userFileFilter,
    limits: { fileSize: 10 * 1024 * 1024 }
});

// const portfolioFilter = (req, file, cb) => {
//     if(file.mimetype.startsWith("image/") || file.mimetype === "application/pdf"){
//         cd(null, true);
//     } else {
//         cb(new Error("Only images and PDF files are allowed!"), false);        
//     }
// };

// const licenseFilter = (req, file, cb) => {
//     if(file.mimetype === "application/pdf"){
//         cb(null, true);
//     } else {
//         cb(new Error("Only PDF files are allowed for pest control license!"), false);
//     }
// }

// // const userUpload = multer({ storage: userStorage });
// const uploadPortfolio = multer({
//     storage: userStorage,
//     fileFilter: portfolioFilter,
//     limits: { fileSize: 10 * 1024 * 1024 } 
// });

// const uploadLicense = multer({
//     storage: userStorage,
//     fileFilter: licenseFilter,
//     limits: { fileSize: 10 * 1024 * 1024 } 
// });

module.exports = {
    verifyUser,
    userUpload
};