const CellGroup = require('../models/cellGroupModel');
const User = require('../models/userModel');

const cellGroupController = {
    getAllCellGroups: async (req, res, next) => {
        try {
            // Get all cell groups
            const cellGroups = await CellGroup.getAll();
            
            // For each cell group, get leader details
            const cellGroupsWithDetails = await Promise.all(cellGroups.map(async (group) => {
                const leader = group.cell_group_leader ? await User.findById(group.cell_group_leader) : null;
                
                return {
                    ...group,
                    leader: leader ? {
                        id: leader.id,
                        first_name: leader.first_name,
                        last_name: leader.last_name,
                        role: leader.role,
                        email: leader.email,
                        profile_url: leader.profile_url || null
                    } : null
                };
            }));
            
            res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Success",
                data: cellGroupsWithDetails
            });
        } catch (error) {
            next(error);
        }
    },

    getCellGroupById: async (req, res, next) => {
        try {
            const { id } = req.body;
            
            if (!id) {
                return res.status(400).json({ 
                    success: false,
                    statusCode: 400,
                    message: 'Cell group ID is required in request body' 
                });
            }

            const group = await CellGroup.getById(id);
            
            if (!group) {
                return res.status(404).json({ 
                    success: false,
                    statusCode: 404,
                    message: 'Cell group not found' 
                });
            }
            
            const leader = group.cell_group_leader ? await User.findById(group.cell_group_leader) : null;
            
            res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Success",
                data: {
                    ...group,
                    leader: leader ? {
                        id: leader.id,
                        first_name: leader.first_name,
                        last_name: leader.last_name,
                        role: leader.role,
                        email: leader.email,
                        profile_url: leader.profile_url || null
                    } : null
                }
            });
        } catch (error) {
            next(error);
        }
    },

    createCellGroup: async (req, res, next) => {
        try {
            const { name, location_name, location_address, location_latitude, location_longitude } = req.body;

            // Validate required fields
            if (!name || !location_name || !location_address) {
                return res.status(400).json({
                    success: false,
                    statusCode: 400,
                    message: "Name, location name, and address are required"
                });
            }

            // Create cell group
            const newGroupId = await CellGroup.create(
                name, 
                location_name, 
                location_address, 
                location_latitude, 
                location_longitude
            );

            // Get the newly created group
            const newGroup = await CellGroup.getById(newGroupId);

            res.status(201).json({
                success: true,
                statusCode: 201,
                message: "Cell group created successfully",
                data: newGroup
            });

        } catch (error) {
            console.error('Cell group creation error:', error);
            next(error);
        }
    },

    updateCellGroup: async (req, res, next) => {
        try {
            const { id, name, location_name, location_address, location_latitude, location_longitude } = req.body;

            if (!id) {
                return res.status(400).json({
                    success: false,
                    statusCode: 400,
                    message: "Cell group ID is required"
                });
            }

            // Check if group exists
            const existingGroup = await CellGroup.getById(id);
            if (!existingGroup) {
                return res.status(404).json({
                    success: false,
                    statusCode: 404,
                    message: "Cell group not found"
                });
            }

            // Update cell group
            const success = await CellGroup.update(
                id,
                name || existingGroup.name,
                location_name || existingGroup.location_name,
                location_address || existingGroup.location_address,
                location_latitude || existingGroup.location_latitude,
                location_longitude || existingGroup.location_longitude
            );

            if (!success) {
                return res.status(500).json({
                    success: false,
                    statusCode: 500,
                    message: "Failed to update cell group"
                });
            }

            // Get updated group details
            const updatedGroup = await CellGroup.getById(id);

            res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Cell group updated successfully",
                data: updatedGroup
            });

        } catch (error) {
            console.error('Cell group update error:', error);
            next(error);
        }
    },

    deleteCellGroup: async (req, res, next) => {
        try {
            const { id } = req.body;

            if (!id) {
                return res.status(400).json({
                    success: false,
                    statusCode: 400,
                    message: "Cell group ID is required"
                });
            }

            // Check if group exists
            const existingGroup = await CellGroup.getById(id);
            if (!existingGroup) {
                return res.status(404).json({
                    success: false,
                    statusCode: 404,
                    message: "Cell group not found"
                });
            }

            // Delete cell group
            const success = await CellGroup.remove(id);

            if (!success) {
                return res.status(500).json({
                    success: false,
                    statusCode: 500,
                    message: "Failed to delete cell group"
                });
            }

            res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Cell group deleted successfully"
            });

        } catch (error) {
            console.error('Cell group deletion error:', error);
            next(error);
        }
    },

    assignLeader: async (req, res, next) => {
        try {
            const { id, userId } = req.body;

            if (!id || !userId) {
                return res.status(400).json({
                    success: false,
                    statusCode: 400,
                    message: "Both cell group ID and user ID are required"
                });
            }

            // Check if group exists
            const existingGroup = await CellGroup.getById(id);
            if (!existingGroup) {
                return res.status(404).json({
                    success: false,
                    statusCode: 404,
                    message: "Cell group not found"
                });
            }

            // Check if user exists
            const user = await User.findById(userId);
            if (!user) {
                return res.status(404).json({
                    success: false,
                    statusCode: 404,
                    message: "User not found"
                });
            }

            // Assign leader
            const success = await CellGroup.assignLeader(id, userId);

            if (!success) {
                return res.status(500).json({
                    success: false,
                    statusCode: 500,
                    message: "Failed to assign leader"
                });
            }

            // Get updated group details
            const updatedGroup = await CellGroup.getById(id);
            const leader = await User.findById(updatedGroup.cell_group_leader);

            res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Leader assigned successfully",
                data: {
                    ...updatedGroup,
                    leader: leader ? {
                        id: leader.id,
                        first_name: leader.first_name,
                        last_name: leader.last_name,
                        role: leader.role,
                        email: leader.email,
                        profile_url: leader.profile_url || null
                    } : null
                }
            });

        } catch (error) {
            console.error('Leader assignment error:', error);
            next(error);
        }
    },

    getCellGroupsByLeader: async (req, res, next) => {
        try {
            const { leaderId } = req.body;
            
            if (!leaderId) {
                return res.status(400).json({
                    success: false,
                    statusCode: 400,
                    message: "Leader ID is required"
                });
            }

            // Check if user exists
            const user = await User.findById(leaderId);
            if (!user) {
                return res.status(404).json({
                    success: false,
                    statusCode: 404,
                    message: "User not found"
                });
            }

            // Get cell groups led by this user
            const cellGroups = await CellGroup.getByLeader(leaderId);
            
            res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Success",
                data: cellGroups
            });
        } catch (error) {
            next(error);
        }
    }
};

module.exports = cellGroupController;