package com.rjlresaka.servlet;

import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;

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.model.User;
import com.rjlresaka.util.TokenUtil;

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

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

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String email = request.getParameter("email");
        if (email == null || email.trim().isEmpty()) {
            request.setAttribute("error", "Entrez votre adresse email.");
            request.getRequestDispatcher("/WEB-INF/views/auth/forgot-password.jsp").forward(request, response);
            return;
        }

        try {
            User user = userDAO.findByEmail(email.trim().toLowerCase(), getServletContext());
            if (user == null) {
                request.setAttribute("error", "Aucun compte trouvé avec cet email.");
                request.getRequestDispatcher("/WEB-INF/views/auth/forgot-password.jsp").forward(request, response);
                return;
            }

            String token = TokenUtil.randomToken(40);
            Timestamp expiresAt = Timestamp.valueOf(LocalDateTime.now().plusMinutes(30));
            passwordResetDAO.createToken(user.getId(), token, expiresAt, getServletContext());

            request.setAttribute("success", "Lien de réinitialisation généré. Branchez ensuite JavaMail pour l'envoyer par email.");
            request.setAttribute("generatedToken", token);
            request.setAttribute("resetLink", request.getContextPath() + "/reset-password?token=" + token);
            request.getRequestDispatcher("/WEB-INF/views/auth/forgot-password.jsp").forward(request, response);
        } catch (Exception exception) {
            request.setAttribute("error", "Réinitialisation impossible pour le moment.");
            request.setAttribute("debugMessage", exception.getMessage());
            request.getRequestDispatcher("/WEB-INF/views/auth/forgot-password.jsp").forward(request, response);
        }
    }
}
