package com.eactive.httpmockserver.user.controller;

import com.eactive.httpmockserver.user.dto.PasswordChangeRequestDTO;
import com.eactive.httpmockserver.user.entity.StaffUser;
import com.eactive.httpmockserver.user.entity.User;
import com.eactive.httpmockserver.user.service.UserService;
import com.eactive.httpmockserver.common.security.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class AccountController {

    @Autowired
    private Validator validator;

    @Autowired
    private UserService userService;

    @GetMapping("/change_password.do")
    public String changePassword(ModelMap model, @ModelAttribute("passwordChangeRequest") PasswordChangeRequestDTO passwordChangeRequestDTO) {
        return "page/updatePw";
    }

    @PostMapping(value = "/update_password.do")
    @Transactional
    public String updatePassword(ModelMap model, @ModelAttribute("passwordChangeRequest") PasswordChangeRequestDTO passwordChangeRequestDTO,
                                 @CurrentUser StaffUser user,
                                 BindingResult result) {

        validator.validate(passwordChangeRequestDTO, result);

        if (result.hasErrors()) {
            model.addAttribute("errors", result);
            return "page/updatePw";
        }

        String oldPassword = passwordChangeRequestDTO.getOldPassword();
        String newPassword = passwordChangeRequestDTO.getNewPassword();
        String newPassword2 = passwordChangeRequestDTO.getNewPassword2();

        String resultMsg = userService.updateUserPassword(user.getUserId(), oldPassword, newPassword, newPassword2);

        model.addAttribute("resultMsg", resultMsg);
        model.addAttribute("passwordChangeRequest", new PasswordChangeRequestDTO());

        return "page/updatePw";
    }


}
