package com.mzh.library.controller;

import com.mzh.library.dao.impl.JdbcSystemLogDao;
import com.mzh.library.dao.impl.JdbcUserDao;
import com.mzh.library.entity.AuthenticatedUser;
import com.mzh.library.entity.Role;
import com.mzh.library.entity.User;
import com.mzh.library.entity.UserSearchCriteria;
import com.mzh.library.service.ServiceResult;
import com.mzh.library.service.UserAccountService;
import com.mzh.library.service.impl.UserAccountServiceImpl;
import com.mzh.library.util.SessionAttributes;

import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

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

public class UserManagementServlet extends HttpServlet {
    private static final String MANAGE_JSP = "/WEB-INF/jsp/admin/users/manage.jsp";
    private static final String FORM_JSP = "/WEB-INF/jsp/admin/users/form.jsp";
    private static final String UNAUTHORIZED_JSP = "/WEB-INF/jsp/auth/unauthorized.jsp";
    private static final String FLASH_SUCCESS = "flashSuccess";
    private static final String FLASH_ERROR = "flashError";
    private static final String DENIED_MESSAGE = "您无权管理用户。";

    private UserAccountService userAccountService;

    @Override
    public void init() {
        JdbcUserDao userDao = new JdbcUserDao();
        this.userAccountService = new UserAccountServiceImpl(userDao, new JdbcSystemLogDao());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        if ("/admin/users/new".equals(path)) {
            renderForm(request, response, "创建用户账户", "/admin/users", defaultUser(),
                Collections.emptyMap(), Collections.emptyMap(), null);
            return;
        }
        if ("/admin/users/edit".equals(path)) {
            showEditForm(request, response);
            return;
        }
        if (!"/admin/users".equals(path)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        showManagementList(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        if ("/admin/users".equals(path)) {
            createUser(request, response);
            return;
        }
        if ("/admin/users/update".equals(path)) {
            updateUser(request, response);
            return;
        }
        if ("/admin/users/deactivate".equals(path)) {
            deactivateUser(request, response);
            return;
        }

        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

    private void showManagementList(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        UserSearchCriteria criteria = searchCriteria(request);
        request.setAttribute("criteria", criteria);
        request.setAttribute("roles", Role.values());
        applyFlash(request);

        ServiceResult<List<User>> result = userAccountService.searchUsers(currentUser(request), criteria);
        if (isPermissionDenied(result)) {
            forwardDenied(request, response, result.getMessage());
            return;
        }

        request.setAttribute("users", result.isSuccessful() ? result.getData() : Collections.emptyList());
        if (!result.isSuccessful()) {
            request.setAttribute("errorMessage", result.getMessage());
            request.setAttribute("errors", result.getErrors());
        }
        request.getRequestDispatcher(MANAGE_JSP).forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long id = requiredLong(request.getParameter("id"), -1L);
        ServiceResult<Optional<User>> result = userAccountService.findUser(currentUser(request), id);
        if (isPermissionDenied(result)) {
            forwardDenied(request, response, result.getMessage());
            return;
        }
        if (!result.isSuccessful() || !result.getData().isPresent()) {
            flashError(request, result.isSuccessful() ? "未找到用户账户。" : result.getMessage());
            response.sendRedirect(request.getContextPath() + "/admin/users");
            return;
        }

        renderForm(request, response, "编辑用户账户", "/admin/users/update", result.getData().get(),
            Collections.emptyMap(), Collections.emptyMap(), null);
    }

    private void createUser(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        UserForm form = readUserForm(request, false);
        if (!form.getErrors().isEmpty()) {
            renderForm(request, response, "创建用户账户", "/admin/users", form.getUser(), form.getValues(),
                form.getErrors(), "请修正高亮的账户字段。");
            return;
        }

        ServiceResult<Long> result = userAccountService.createUser(currentUser(request), form.getUser(),
            form.getPassword(), clientIp(request));
        if (!result.isSuccessful()) {
            handleFormFailure(request, response, "创建用户账户", "/admin/users", form, result);
            return;
        }

        flashSuccess(request, result.getMessage());
        response.sendRedirect(request.getContextPath() + "/admin/users");
    }

    private void updateUser(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        UserForm form = readUserForm(request, true);
        if (!form.getErrors().isEmpty()) {
            renderForm(request, response, "编辑用户账户", "/admin/users/update", form.getUser(), form.getValues(),
                form.getErrors(), "请修正高亮的账户字段。");
            return;
        }

        ServiceResult<Void> result = userAccountService.updateUser(currentUser(request), form.getUser(),
            form.getPassword(), clientIp(request));
        if (!result.isSuccessful()) {
            handleFormFailure(request, response, "编辑用户账户", "/admin/users/update", form, result);
            return;
        }

        flashSuccess(request, result.getMessage());
        response.sendRedirect(request.getContextPath() + "/admin/users");
    }

    private void deactivateUser(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        long id = requiredLong(request.getParameter("id"), -1L);
        ServiceResult<Void> result = userAccountService.deactivateUser(currentUser(request), id, clientIp(request));
        if (isPermissionDenied(result)) {
            forwardDenied(request, response, result.getMessage());
            return;
        }
        if (result.isSuccessful()) {
            flashSuccess(request, result.getMessage());
        } else {
            flashError(request, result.getMessage());
        }
        response.sendRedirect(request.getContextPath() + "/admin/users");
    }

    private void handleFormFailure(HttpServletRequest request, HttpServletResponse response, String title,
                                   String action, UserForm form, ServiceResult<?> result)
        throws ServletException, IOException {
        if (isPermissionDenied(result)) {
            forwardDenied(request, response, result.getMessage());
            return;
        }
        renderForm(request, response, title, action, form.getUser(), form.getValues(), result.getErrors(),
            result.getMessage());
    }

    private void renderForm(HttpServletRequest request, HttpServletResponse response, String title, String action,
                            User user, Map<String, String> formValues, Map<String, String> errors,
                            String errorMessage)
        throws ServletException, IOException {
        request.setAttribute("roles", Role.values());
        request.setAttribute("formTitle", title);
        request.setAttribute("formAction", action);
        request.setAttribute("user", user);
        request.setAttribute("formValues", formValues);
        request.setAttribute("errors", errors);
        if (errorMessage != null && !errorMessage.isEmpty()) {
            request.setAttribute("errorMessage", errorMessage);
        }
        request.getRequestDispatcher(FORM_JSP).forward(request, response);
    }

    private UserForm readUserForm(HttpServletRequest request, boolean requireId) {
        Map<String, String> values = formValues(request);
        Map<String, String> errors = new LinkedHashMap<>();
        User user = new User();

        if (requireId) {
            user.setId(parseLong(values.get("id"), "id", "请选择有效的用户账户。", errors));
        }
        user.setUsername(values.get("username"));
        user.setDisplayName(values.get("displayName"));
        user.setActive(parseActive(values.get("active"), errors));
        try {
            user.setRole(Role.fromCode(values.get("role")));
        } catch (IllegalArgumentException ex) {
            errors.put("role", "请选择角色。");
        }

        return new UserForm(user, values, errors, request.getParameter("password"));
    }

    private Map<String, String> formValues(HttpServletRequest request) {
        Map<String, String> values = new LinkedHashMap<>();
        values.put("id", trim(request.getParameter("id")));
        values.put("username", trim(request.getParameter("username")));
        values.put("displayName", trim(request.getParameter("displayName")));
        values.put("role", trim(request.getParameter("role")));
        values.put("active", trim(request.getParameter("active")));
        return values;
    }

    private UserSearchCriteria searchCriteria(HttpServletRequest request) {
        return new UserSearchCriteria(
            request.getParameter("keyword"),
            request.getParameter("role"),
            request.getParameter("active")
        );
    }

    private User defaultUser() {
        User user = new User();
        user.setRole(Role.READER);
        user.setActive(true);
        return user;
    }

    private boolean parseActive(String value, Map<String, String> errors) {
        String normalized = trim(value);
        if ("true".equals(normalized) || UserSearchCriteria.ACTIVE_STATUS.equals(normalized)) {
            return true;
        }
        if ("false".equals(normalized) || UserSearchCriteria.INACTIVE_STATUS.equals(normalized)) {
            return false;
        }
        errors.put("active", "请选择启用状态。");
        return false;
    }

    private long parseLong(String value, String field, String message, Map<String, String> errors) {
        String trimmed = trim(value);
        if (trimmed.isEmpty()) {
            errors.put(field, message);
            return 0L;
        }
        try {
            long parsed = Long.parseLong(trimmed);
            if (parsed <= 0) {
                errors.put(field, message);
            }
            return parsed;
        } catch (NumberFormatException ex) {
            errors.put(field, message);
            return 0L;
        }
    }

    private long requiredLong(String value, long fallback) {
        try {
            long parsed = Long.parseLong(trim(value));
            return parsed > 0 ? parsed : fallback;
        } catch (NumberFormatException ex) {
            return fallback;
        }
    }

    private boolean isPermissionDenied(ServiceResult<?> result) {
        return !result.isSuccessful() && DENIED_MESSAGE.equals(result.getMessage());
    }

    private void forwardDenied(HttpServletRequest request, HttpServletResponse response, String message)
        throws ServletException, IOException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        request.setAttribute("errorMessage", message);
        request.getRequestDispatcher(UNAUTHORIZED_JSP).forward(request, response);
    }

    private AuthenticatedUser currentUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        Object value = session == null ? null : session.getAttribute(SessionAttributes.AUTHENTICATED_USER);
        return value instanceof AuthenticatedUser ? (AuthenticatedUser) value : null;
    }

    private void applyFlash(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        moveFlash(session, request, FLASH_SUCCESS, "successMessage");
        moveFlash(session, request, FLASH_ERROR, "errorMessage");
    }

    private void moveFlash(HttpSession session, HttpServletRequest request, String sessionKey, String requestKey) {
        Object value = session.getAttribute(sessionKey);
        if (value != null) {
            request.setAttribute(requestKey, value);
            session.removeAttribute(sessionKey);
        }
    }

    private void flashSuccess(HttpServletRequest request, String message) {
        request.getSession().setAttribute(FLASH_SUCCESS, message);
    }

    private void flashError(HttpServletRequest request, String message) {
        request.getSession().setAttribute(FLASH_ERROR, message);
    }

    private String clientIp(HttpServletRequest request) {
        return trim(request.getRemoteAddr());
    }

    private String trim(String value) {
        return value == null ? "" : value.trim();
    }

    private static final class UserForm {
        private final User user;
        private final Map<String, String> values;
        private final Map<String, String> errors;
        private final String password;

        private UserForm(User user, Map<String, String> values, Map<String, String> errors, String password) {
            this.user = user;
            this.values = values;
            this.errors = errors;
            this.password = password;
        }

        private User getUser() {
            return user;
        }

        private Map<String, String> getValues() {
            return values;
        }

        private Map<String, String> getErrors() {
            return errors;
        }

        private String getPassword() {
            return password;
        }
    }
}
