package com.rjlresaka.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rjlresaka.dao.MessageDAO;
import com.rjlresaka.model.User;

@WebServlet("/app/messages/update")
public class UpdateMessageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final MessageDAO messageDAO = new MessageDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("authUser") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        User authUser = (User) session.getAttribute("authUser");
        int conversationId = parseInt(request.getParameter("conversationId"));
        int messageId = parseInt(request.getParameter("messageId"));
        String body = request.getParameter("body");

        try {
            boolean updated = messageDAO.updateMessage(messageId, authUser.getId(), body, getServletContext());
            session.setAttribute(updated ? "flashSuccess" : "flashError",
                    updated ? "Message modifié." : "Modification refusée.");
        } catch (Exception exception) {
            session.setAttribute("flashError", "Erreur de modification : " + exception.getMessage());
        }
        response.sendRedirect(request.getContextPath() + "/app/dashboard?conversation=" + conversationId);
    }

    private int parseInt(String value) {
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException exception) {
            return 0;
        }
    }
}
