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

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final UserDAO userDAO = new UserDAO();

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

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

        if (identity == null || identity.trim().isEmpty() || password == null || password.isEmpty()) {
            request.setAttribute("error", "Veuillez remplir votre email/username et votre mot de passe.");
            request.getRequestDispatcher("/WEB-INF/views/auth/login.jsp").forward(request, response);
            return;
        }

        try {
            User user = userDAO.findByEmailOrUsername(identity.trim(), getServletContext());
            if (user == null || !PasswordUtil.verify(password, user.getPasswordHash())) {
                request.setAttribute("error", "Identifiants invalides.");
                request.getRequestDispatcher("/WEB-INF/views/auth/login.jsp").forward(request, response);
                return;
            }

            HttpSession session = request.getSession();
            session.setAttribute("authUser", user);
            response.sendRedirect(request.getContextPath() + "/app/dashboard");
        } catch (Exception exception) {
            request.setAttribute("error", "Connexion impossible pour le moment. Vérifiez votre base MySQL.");
            request.setAttribute("debugMessage", exception.getMessage());
            request.getRequestDispatcher("/WEB-INF/views/auth/login.jsp").forward(request, response);
        }
    }
}
