const express = require('express');
const Message = require('../models/Message');
const User = require('../models/User');
const { authenticateToken, isAdmin } = require('../middleware/auth');
const router = express.Router();

// GET conversation for a user
router.get('/conversation/:userId', authenticateToken, async (req, res) => {
    try {
        const userId = req.params.userId;
        const conversationId = `user_${userId}`;
        
        const messages = await Message.findAll({
            where: { conversation_id: conversationId },
            order: [['createdAt', 'ASC']],
            include: [
                {
                    model: User,
                    as: 'sender',
                    attributes: ['id', 'name', 'email', 'role']
                }
            ]
        });

        res.json(messages);
    } catch (error) {
        console.error('Error fetching conversation:', error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// GET all conversations (Admin only)
router.get('/conversations', authenticateToken, isAdmin, async (req, res) => {
    try {
        // Get all messages grouped by conversation
        const allMessages = await Message.findAll({
            order: [['created_at', 'DESC']]
        });

        // Group by conversation_id
        const conversationsMap = new Map();
        
        for (const msg of allMessages) {
            if (!conversationsMap.has(msg.conversation_id)) {
                const userId = msg.conversation_id.replace('user_', '');
                const user = await User.findByPk(userId, {
                    attributes: ['id', 'name', 'email', 'image']
                });

                // Count unread messages (user messages that are not read)
                const unreadCount = allMessages.filter(m => 
                    m.conversation_id === msg.conversation_id && 
                    !m.is_admin && 
                    !m.is_read
                ).length;

                conversationsMap.set(msg.conversation_id, {
                    conversation_id: msg.conversation_id,
                    user: user,
                    unread_count: unreadCount,
                    last_message: {
                        message: msg.message,
                        is_admin: msg.is_admin,
                        created_at: msg.created_at
                    },
                    last_message_at: msg.created_at
                });
            }
        }

        const conversations = Array.from(conversationsMap.values());
        res.json(conversations);
    } catch (error) {
        console.error('Error fetching conversations:', error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// POST send message
router.post('/', authenticateToken, async (req, res) => {
    try {
        const { message, conversation_id } = req.body;
        const isUserAdmin = req.user.role === 'admin';
        
        let conversationId = conversation_id;
        let userId = null;
        let adminId = null;

        if (isUserAdmin) {
            // Admin sending message
            adminId = req.user.id;
            // Extract user ID from conversation_id
            userId = parseInt(conversationId.replace('user_', ''));
        } else {
            // User sending message
            userId = req.user.id;
            conversationId = `user_${userId}`;
        }

        const newMessage = await Message.create({
            user_id: userId,
            admin_id: adminId,
            conversation_id: conversationId,
            message: message,
            is_admin: isUserAdmin,
            is_read: false
        });

        // Fetch with user info
        const messageWithUser = await Message.findByPk(newMessage.id, {
            include: [
                {
                    model: User,
                    as: 'sender',
                    attributes: ['id', 'name', 'email', 'role']
                }
            ]
        });

        res.status(201).json(messageWithUser);
    } catch (error) {
        console.error('Error sending message:', error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// PUT mark message as read
router.put('/:id/read', authenticateToken, async (req, res) => {
    try {
        const message = await Message.findByPk(req.params.id);
        if (!message) {
            return res.status(404).json({ message: 'Message not found' });
        }

        await message.update({ is_read: true });
        res.json(message);
    } catch (error) {
        console.error('Error marking message as read:', error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// GET admin online status
router.get('/admin-status', async (req, res) => {
    try {
        // Check if any admin was active in last 5 minutes
        const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
        
        const { Op } = require('sequelize');
        const onlineAdmin = await User.findOne({
            where: {
                role: 'admin',
                last_seen: {
                    [Op.gte]: fiveMinutesAgo
                }
            },
            attributes: ['id', 'name', 'last_seen']
        });

        console.log('Checking admin status:');
        console.log('Five minutes ago:', fiveMinutesAgo);
        console.log('Online admin found:', onlineAdmin ? `${onlineAdmin.name} (last seen: ${onlineAdmin.last_seen})` : 'None');

        res.json({
            online: !!onlineAdmin,
            admin: onlineAdmin ? { id: onlineAdmin.id, name: onlineAdmin.name } : null
        });
    } catch (error) {
        console.error('Error checking admin status:', error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

module.exports = router;
