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 com.rjlresaka.dao.PasswordResetDAO;
import com.rjlresaka.dao.UserDAO;
import com.rjlresaka.util.PasswordUtil;

@WebServlet("/reset-password")
public class ResetPasswordServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final PasswordResetDAO passwordResetDAO = new PasswordResetDAO();
    private final UserDAO userDAO = new UserDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/views/auth/reset-password.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String token = request.getParameter("token");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");

        if (token == null || token.trim().isEmpty()) {
            request.setAttribute("error", "Le token de réinitialisation est manquant.");
            request.getRequestDispatcher("/WEB-INF/views/auth/reset-password.jsp").forward(request, response);
            return;
        }

        if (password == null || password.length() < 6) {
            request.setAttribute("error", "Le nouveau mot de passe doit contenir au moins 6 caractères.");
            request.setAttribute("token", token);
            request.getRequestDispatcher("/WEB-INF/views/auth/reset-password.jsp").forward(request, response);
            return;
        }

        if (!password.equals(confirmPassword)) {
            request.setAttribute("error", "La confirmation du mot de passe ne correspond pas.");
            request.setAttribute("token", token);
            request.getRequestDispatcher("/WEB-INF/views/auth/reset-password.jsp").forward(request, response);
            return;
        }

        try {
            Integer userId = passwordResetDAO.findValidUserIdByToken(token.trim(), getServletContext());
            if (userId == null) {
                request.setAttribute("error", "Le lien est invalide ou expiré.");
                request.setAttribute("token", token);
                request.getRequestDispatcher("/WEB-INF/views/auth/reset-password.jsp").forward(request, response);
                return;
            }

            userDAO.updatePassword(userId.intValue(), PasswordUtil.hash(password), getServletContext());
            passwordResetDAO.markAsUsed(token.trim(), getServletContext());
            request.setAttribute("success", "Mot de passe mis à jour. Vous pouvez vous connecter.");
            request.getRequestDispatcher("/WEB-INF/views/auth/login.jsp").forward(request, response);
        } catch (Exception exception) {
            request.setAttribute("error", "Impossible de mettre à jour le mot de passe.");
            request.setAttribute("debugMessage", exception.getMessage());
            request.setAttribute("token", token);
            request.getRequestDispatcher("/WEB-INF/views/auth/reset-password.jsp").forward(request, response);
        }
    }
}
