const SubSubCatagory = require('../models/SubSubCatagory');



// This is the controller file to fasten the trade site pages


// GET: /api/trade/getfiltersbytypets/:type
exports.getFiltersByTypeTS = async (req, res) => {
    const { type } = req.params;
    try {
        let aggregation = [
            { $match: { typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" } } },
            { $unwind: { path: "$color", preserveNullAndEmptyArrays: true } },
            {
                $group: {
                    _id: null,
                    Manufacturers: { $addToSet: "$manufacturerName" },
                    Variants: { $addToSet: "$variantName" },
                    Colors: { $addToSet: "$color.name" },
                    minPrice: { $min: "$wholesellerPrice" },
                    maxPrice: { $max: "$wholesellerPrice" }
                }
            },
            {
                $project: {
                    _id: 0,
                    Manufacturers: 1,
                    Variants: 1,
                    Colors: 1,
                    minPrice: 1,
                    maxPrice: 1
                }
            }
        ];
        const data = await SubSubCatagory.aggregate(aggregation);
        const { Manufacturers, Variants, Colors, minPrice, maxPrice } = data[0];
        return res.status(200).json({
            success: true, message: "Filters for this type are found", filters: {
                Manufacturers: Manufacturers.sort((a, b) => a.localeCompare(b)),
                Variants: Variants.sort((a, b) => a.localeCompare(b)),
                Colors: Colors.sort((a, b) => a.localeCompare(b))
            }, minPrice, maxPrice
        });
    } catch (error) {
        console.log('Error getting subsubcatagries', error);
        return res.status(500).json({ success: false, message: error?.message ?? "Internal Server Error" });
    }
}



// GET: /api/trade/getaccessbytypets/:type?limit=&page=&manufacturer=&variant=&color=$min=$max=
exports.getAccessByTypeTS = async (req, res) => {
    const { type } = req.params;
    let { limit, page, manufacturer, variant, color, min, max } = req.query;
    limit = Number(limit) || 30;
    page = Number(page) || 1;
    const skip = (page - 1) * limit;
    let availableQueries = [];
    try {
        if (manufacturer) {
            if (Array.isArray(manufacturer)) {
                const manufQueries = manufacturer.map(manuf => ({ manufacturerName: { $regex: `^\\s*${manuf}\\s*$`, $options: "i" } }));
                availableQueries.push({ $or: manufQueries });
            } else {
                availableQueries.push({ manufacturerName: { $regex: `^\\s*${manufacturer}\\s*$`, $options: "i" } });
            }
        }
        if (color) {
            if (Array.isArray(color)) {
                const colorQueries = color.map(colorName => ({ color: { $elemMatch: { name: colorName } } }));
                availableQueries.push({ $or: colorQueries });
            } else {
                availableQueries.push({ color: { $elemMatch: { name: color } } });
            }
        }
        if (variant) {
            if (Array.isArray(variant)) {
                const variantQueries = variant.map((variant) => ({ variantName: { $regex: `^\\s*${variant}\\s*$`, $options: "i" } }));
                availableQueries.push({ $or: variantQueries });
            } else {
                availableQueries.push({ variantName: { $regex: `^\\s*${variant}\\s*$`, $options: "i" } });
            }
        }

        if (min || max) {
            if (min) {
                availableQueries = [{ wholesellerPrice: { $gte: Number(min) } }, ...availableQueries];
            }
            if (max) {
                availableQueries = [{ wholesellerPrice: { $lte: Number(max) } }, ...availableQueries];
            }
        }

        if (availableQueries.length === 0) {
            availableQueries.push({});
        }

        let aggregation = [
            { $match: { typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" } } },
            { $match: { $and: availableQueries } },
            { $skip: skip },
            { $limit: limit },
        ]
        const subsubcatagories = await SubSubCatagory.aggregate(aggregation);
        const totalDocuments = await SubSubCatagory.countDocuments({
            typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" },
            $and: availableQueries
        });
        const totalPages = Math.ceil(totalDocuments / limit);
        return res.status(200).json({ success: true, message: "Filters for this type are found", subsubcatagories, totalPages, page, limit });
    } catch (error) {
        console.log('Error getting subsubcatagries', error);
        return res.status(500).json({ success: false, message: error?.message ?? "Internal Server Error" });
    }
}





// GET: /api/trade/getfiltersbytypeandbrandts/:type/:brand
exports.getFiltersByTypeAndBrandTS = async (req, res) => {
    const { type, brand } = req.params;
    try {
        let aggregation = [
            {
                $match: {
                    typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" },
                    catagory: { $regex: `^\\s*${brand}\\s*$`, $options: "i" }
                },
            },
            { $unwind: { path: "$color", preserveNullAndEmptyArrays: true } },
            {
                $group: {
                    _id: null,
                    Manufacturers: { $addToSet: "$manufacturerName" },
                    Variants: { $addToSet: "$variantName" },
                    Colors: { $addToSet: "$color.name" },
                    minPrice: { $min: "$wholesellerPrice" },
                    maxPrice: { $max: "$wholesellerPrice" }
                }
            },
            {
                $project: {
                    _id: 0,
                    Manufacturers: 1,
                    Variants: 1,
                    Colors: 1,
                    minPrice: 1,
                    maxPrice: 1
                }
            }
        ];
        const data = await SubSubCatagory.aggregate(aggregation);
        const { Manufacturers, Variants, Colors, minPrice, maxPrice } = data[0];
        return res.status(200).json({
            success: true, message: "Filters for this type and brand are found", filters: {
                Manufacturers: Manufacturers.sort((a, b) => a.localeCompare(b)),
                Variants: Variants.sort((a, b) => a.localeCompare(b)),
                Colors: Colors.sort((a, b) => a.localeCompare(b))
            }, minPrice, maxPrice
        });
    } catch (error) {
        console.log('Error getting subsubcatagries', error);
        return res.status(500).json({ success: false, message: error?.message ?? "Internal Server Error" });
    }
}





// GET: /api/trade/getaccesssbytypeandbrandts/:type/:brand?limit=&page=&manufacturer=&variant=&color=$min=$max=
exports.getAccesssByTypeAndBrandTS = async (req, res) => {
    const { type, brand } = req.params;
    let { limit, page, manufacturer, variant, color, min, max } = req.query;
    limit = Number(limit) || 30;
    page = Number(page) || 1;
    const skip = (page - 1) * limit;
    let availableQueries = [];
    try {
        if (manufacturer) {
            if (Array.isArray(manufacturer)) {
                const manufQueries = manufacturer.map(manuf => ({ manufacturerName: { $regex: `^\\s*${manuf}\\s*$`, $options: "i" } }));
                availableQueries.push({ $or: manufQueries });
            } else {
                availableQueries.push({ manufacturerName: { $regex: `^\\s*${manufacturer}\\s*$`, $options: "i" } });
            }
        }
        if (color) {
            if (Array.isArray(color)) {
                const colorQueries = color.map(colorName => ({ color: { $elemMatch: { name: colorName } } }));
                availableQueries.push({ $or: colorQueries });
            } else {
                availableQueries.push({ color: { $elemMatch: { name: color } } });
            }
        }
        if (variant) {
            if (Array.isArray(variant)) {
                const variantQueries = variant.map((variant) => ({ variantName: { $regex: `^\\s*${variant}\\s*$`, $options: "i" } }));
                availableQueries.push({ $or: variantQueries });
            } else {
                availableQueries.push({ variantName: { $regex: `^\\s*${variant}\\s*$`, $options: "i" } });
            }
        }

        if (min || max) {
            if (min) {
                availableQueries = [{ wholesellerPrice: { $gte: Number(min) } }, ...availableQueries];
            }
            if (max) {
                availableQueries = [{ wholesellerPrice: { $lte: Number(max) } }, ...availableQueries];
            }
        }

        if (availableQueries.length === 0) {
            availableQueries.push({});
        }

        let aggregation = [
            {
                $match: {
                    typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" },
                    catagory: { $regex: `^\\s*${brand}\\s*$`, $options: "i" }
                }
            },
            { $match: { $and: availableQueries } },
            { $skip: skip },
            { $limit: limit },
        ]
        const subsubcatagories = await SubSubCatagory.aggregate(aggregation);
        const totalDocuments = await SubSubCatagory.countDocuments({
            typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" },
            catagory: { $regex: `^\\s*${brand}\\s*$`, $options: "i" },
            $and: availableQueries
        });
        const totalPages = Math.ceil(totalDocuments / limit);
        return res.status(200).json({ success: true, message: "Filters for this type and brand are found", subsubcatagories, totalPages, page, limit });
    } catch (error) {
        console.log('Error getting subsubcatagries', error);
        return res.status(500).json({ success: false, message: error?.message ?? "Internal Server Error" });
    }
}




// GET: /api/trade/getfiltersbymodelts/:model
exports.getFiltersByModelTS = async (req, res) => {
    const { model } = req.params;
    try {
        let aggregation = [
            {
                $match: {
                    subcatagory: { $regex: `^\\s*${model}\\s*$`, $options: "i" }
                },
            },
            { $unwind: { path: "$color", preserveNullAndEmptyArrays: true } },
            {
                $group: {
                    _id: null,
                    Manufacturers: { $addToSet: "$manufacturerName" },
                    Variants: { $addToSet: "$variantName" },
                    Colors: { $addToSet: "$color.name" },
                    minPrice: { $min: "$wholesellerPrice" },
                    maxPrice: { $max: "$wholesellerPrice" }
                }
            },
            {
                $project: {
                    _id: 0,
                    Manufacturers: 1,
                    Variants: 1,
                    Colors: 1,
                    minPrice: 1,
                    maxPrice: 1
                }
            }
        ];
        const data = await SubSubCatagory.aggregate(aggregation);
        const { Manufacturers, Variants, Colors, minPrice, maxPrice } = data[0];
        return res.status(200).json({ success: true, message: "Filters for this model are found", filters: { Manufacturers, Variants, Colors }, minPrice, maxPrice });
    } catch (error) {
        console.log('Error getting subsubcatagries', error);
        return res.status(500).json({ success: false, message: error?.message ?? "Internal Server Error" });
    }
}






