const Catagory = require("../models/Catagory");
const SubCatagory = require('../models/SubCatagory');
const SubSubCatagory = require('../models/SubSubCatagory');

exports.postNew = async function (req, res) {
    let data = req.body;
    console.log("nnnnnn", data)
    if (
        !data
    ) {
        return res.status(422).json({
            message: "All feilds are required",
        });
    }
    try {
        const catagorie = new Catagory(data);
        const catagories = await catagorie.save();
        res.status(200).json({ message: "success", catagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};

exports.update = async function (req, res) {
    const { id } = req.params;
    const { catagory } = req.body;
    if (
        !catagory
    ) {
        return res.status(422).json({
            message: "All feilds are required",
        });
    }
    try {
        const catagorie = await Catagory.findByIdAndUpdate(id, { catagory }, { new: true });
        await SubCatagory.updateMany({ catagoryid: id }, { catagory });
        await SubSubCatagory.updateMany({ catagoryid: id }, { catagory });
        res.status(200).json({ message: "success", catagorie });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};


exports.updateCatagorySequence = async function (req, res) {
    try {
        const { catagoryId, targetCatagoryId } = req.body;
        // Fetch products
        const [sourceProduct, targetProduct] = await Promise.all([
            Catagory.findById(catagoryId),
            Catagory.findById(targetCatagoryId)
        ]);
        if (!sourceProduct || !targetProduct) {
            return res.status(404).json({ success: false, message: 'Product not found' });
        }
        if (sourceProduct === targetProduct) {
            return res.status(423).json({ success: false, message: 'Same Products cannot be replaced' });
        }
        // Swap the data fields of source and target products
        const updatedSourceProduct = await Catagory.findByIdAndUpdate(catagoryId, {
            catagory: targetProduct.catagory
        }, { new: true });
        const updatedTargetProduct = await Catagory.findByIdAndUpdate(targetCatagoryId, {
            catagory: sourceProduct.catagory
        }, { new: true });
        res.status(200).json({ success: true, message: 'Product sequence updated successfully' });
    } catch (error) {
        console.error('Error updating product sequence:', error);
        res.status(500).json({ success: false, message: 'Internal server error' });
    }
}


exports.AddSubCat = async function (req, res) {
    console.log("nnnnnn", req.body)
    const { subcatagory, imageSubCatagory, catagory } = req.body;

    if (
        !subcatagory ||
        !imageSubCatagory ||
        !catagory
    ) {
        return res.status(422).json({
            message: "All feilds are required",
        });
    }
    try {
        const catagorie = new Catagory({ subcatagory: subcatagory, imageSubCatagory: imageSubCatagory });
        const catagories = await catagorie.updateOne({ _id: catagory });
        res.status(200).json({ message: "success", catagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};

exports.GetAllCatagory = async function (req, res) {  
    try {
        const catagories = await Catagory.find();
        res.status(200).json({ message: "Success", catagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};


exports.GetSingle = async function (req, res) {
    console.log("abc=====", req.params.id);
    let searchQuery = req.params.id;
    try {
        const catagories = await Catagory.find({ item: { $regex: new RegExp(searchQuery, 'i') } });
        res.status(200).json({ message: "Success", catagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};


exports.getDataByID = async function (req, res) {
    let ID = req.params.id;
    try {
        const catagories = await Catagory.findOne({ _id: ID });
        res.status(200).json({ message: "Success", catagories });
    } catch (error) {
        console.log("is match 1st error===>>>", error)
        res.status(404).json({ success: false, message: error.message });
    }
};

exports.DeleteSingl = async function (req, res) {
    let ID = req.params.id;
    try {
        Catagory.deleteOne({ _id: ID }, (err, response) => {
            if (response === null) {
                res.json({ message: "User Not Found" })
            } else {
                console.log("user found")
                res.status(200).json({ response, message: "SuccessDelete" })
            }
        });
    } catch (error) {
        console.log("is match 1st error===>>>")
        res.status(404).json({ success: false, message: error.message });
    }
};