const superAdminModel = require("../models/superAdmin");
const featureModel = require("../models/features");
const userModel = require("../models/userModel");
const shopModel = require("../models/shopModel");
const orderModel = require("../models/order");
const bcrypt = require("bcrypt");

// SuperAdmin Auth Functions
const validateSuperAdmin = async (req) => {
    const existing = await superAdminModel.findOne({ email: req.body.email });
    if(existing){
        return true
    } else {
        return false
    }
};

const createSuperAdmin = async (req) => {
    const newSuperAdmin = new superAdminModel(req.body);
    const hash = await bcrypt.hash(req.body.password, 10);
    newSuperAdmin.password = hash;
    const result = await newSuperAdmin.save();
    return result;
};

const getSuperAdmin = async (req) => {
    const { email } = req.body;

    const superAdmin = await superAdminModel.findOne({ email: email });
    return superAdmin
}
const getSuperAdminProfile = async (req) => {
    const { superAdminId } = req.query;
    const superAdmin = await superAdminModel.findById(superAdminId).select("-password");
    return superAdmin;
};

const updateSuperAdmin = async (req) => {
    const { superAdminId } = req.body;
    const updatedData = req.body;

    const superAdmin = await superAdminModel.findByIdAndUpdate(superAdminId,
        { $set: updatedData },
        { new: true }
    ).select("-password");
    return superAdmin;
};

const resetPassword = async (req) => {
    const { superAdminId, password } = req.body;
    const hash = await bcrypt.hash(password, 10);

    const superAdmin = await superAdminModel.findByIdAndUpdate(superAdminId,
        { $set: { password: hash }},
        { new: true }
    );
    return superAdmin
};

// SuperAdmin Feature Functions
const createFeature = async (req) => {
    const image = req.file.filename;
    const newFeature = new featureModel({
        ...req.body,
        bannerImage: image
    });
    const result = await newFeature.save(); 
    return result;
};

const getFeatureById = async (req) => {
    const { featureId } = req.query;
    const feature = await featureModel.findById(featureId).populate({
       path: "productId"
    });
    return feature
};

const getAllFeatures = async (req) => {
    const { shopId, productId, adminId, isActive } = req.query;
    const filter = {};

    if(shopId){
        filter.shopId = shopId;
    }

    if(productId){
        filter.productId = productId;
    }

    if(adminId){
        filter.adminId = adminId;
    }

    if(isActive){
        filter.isActive = isActive;
    }

    const feature = await featureModel.find(filter).populate({
        path: "shopId",
        select: "barName barDetails"
    }).populate("productId");
    return feature;
};

const updateFeature = async (req) => {
    const { featureId } = req.body;
    const updatedData = req.body;

    if(req.file && req.file.filename){
        updatedData.bannerImage = req.file.filename
    }

    const feature = await featureModel.findByIdAndUpdate(featureId, 
        { $set: updatedData },
        { new: true }
    );
    return feature
};

const deleteFeature = async (req) => {
    const { featureId } = req.body;
    const feature = await featureModel.findByIdAndDelete(featureId);
    return feature
};

const superAdminStats = async (req) => {
    const totalUsers = await userModel.find().countDocuments();
    const totalBars = await shopModel.find().countDocuments();
    const totalOrders = await orderModel.find().countDocuments();
    
    const result = await orderModel.aggregate([
        {
          $group: {
            _id: null, // group all documents together
            totalGrandTotal: { $sum: "$grandTotal" }
          }
        }
    ]);

    const totalGrandTotal = result.length > 0 ? result[0].totalGrandTotal : 0;

    const stats = {
        TotalRevenue: totalGrandTotal,
        totalOrder: totalOrders,
        totalBars: totalBars,
        totalUsers: totalUsers
    };

    return stats
};

module.exports = {
    validateSuperAdmin,
    createSuperAdmin,
    getSuperAdmin,
    getSuperAdminProfile,
    updateSuperAdmin,
    resetPassword,
    createFeature,
    getFeatureById,
    getAllFeatures,
    updateFeature,
    deleteFeature,
    superAdminStats
};