import * as messageService from '../services/message.service.js';

/**
 * Get all conversations for current user
 * GET /api/messages/conversations
 */
export const getConversations = async (req, res, next) => {
  try {
    const conversations = await messageService.getConversations(req.userId);

    res.status(200).json({
      success: true,
      data: conversations,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get messages with a specific user
 * GET /api/messages/conversation/:userId
 */
export const getConversation = async (req, res, next) => {
  const { userId: partnerId } = req.params;

  try {
    const conversation = await messageService.getConversation(req.userId, partnerId);

    res.status(200).json({
      success: true,
      data: conversation,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Send a message to another user
 * POST /api/messages/send
 */
export const sendMessage = async (req, res, next) => {
  const { receiverId, content } = req.body;

  try {
    const message = await messageService.sendMessage(req.userId, receiverId, content);

    res.status(201).json({
      success: true,
      data: message,
      message: 'Správa bola odoslaná',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Delete conversation with a user
 * DELETE /api/messages/conversation/:userId
 */
export const deleteConversation = async (req, res, next) => {
  const { userId: partnerId } = req.params;

  try {
    await messageService.deleteConversation(req.userId, partnerId);

    res.status(200).json({
      success: true,
      message: 'Konverzácia bola odstránená',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get unread message count
 * GET /api/messages/unread-count
 */
export const getUnreadCount = async (req, res, next) => {
  try {
    const count = await messageService.getUnreadCount(req.userId);

    res.status(200).json({
      success: true,
      data: { unreadCount: count },
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get all CRM users available for chat
 * GET /api/messages/users
 */
export const getChatUsers = async (req, res, next) => {
  try {
    const users = await messageService.getChatUsers(req.userId);

    res.status(200).json({
      success: true,
      data: users,
    });
  } catch (error) {
    next(error);
  }
};
