package com.eactive.testmaster.user.controller;

import com.eactive.testmaster.common.util.SecurityUtil;
import com.eactive.testmaster.user.dto.PasswordChangeRequestDTO;
import com.eactive.testmaster.user.entity.User;
import com.eactive.testmaster.user.service.UserService;
import java.util.HashMap;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BeanPropertyBindingResult;
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;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/account")
public class AccountApiController {

    private final Validator validator;
    private final UserService userService;

    public AccountApiController(Validator validator, UserService userService) {
        this.validator = validator;
        this.userService = userService;
    }

    @GetMapping
    @Secured("ROLE_API_TESTER")
    public ResponseEntity<User> account(ModelMap model) {
        return ResponseEntity.ok().body(SecurityUtil.getCurrentUser());
    }


    @PostMapping("/password")
    @Transactional
    @Secured("ROLE_API_TESTER")
    public ResponseEntity<?> updatePassword(@RequestBody PasswordChangeRequestDTO passwordChangeRequestDTO) {
        BindingResult result = new BeanPropertyBindingResult(passwordChangeRequestDTO, "passwordChangeRequest");
        validator.validate(passwordChangeRequestDTO, result);

        if (result.hasErrors()) {
            return ResponseEntity.badRequest().body(result.getAllErrors());
        }

        try {
            String resultMsg = userService.updateUserPassword(
                SecurityUtil.getCurrentUserEsntlId(),
                passwordChangeRequestDTO.getOldPassword(),
                passwordChangeRequestDTO.getNewPassword(),
                passwordChangeRequestDTO.getNewPassword2()
            );

            return ResponseEntity.ok().body(new HashMap<String, String>() {{
                put("message", resultMsg);
            }});
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new HashMap<String, String>() {{
                put("error", e.getMessage());
            }});
        }
    }

}
