package com.eactive.httpmockserver.user.controller;

import com.eactive.httpmockserver.user.dto.UserRegisterDTO;
import com.eactive.httpmockserver.user.entity.StaffUser;
import com.eactive.httpmockserver.user.mapper.StaffUserMapper;
import com.eactive.httpmockserver.user.repository.StaffUserRepository;
import com.eactive.httpmockserver.user.service.StaffUserService;
import org.springframework.stereotype.Controller;
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 AdminRegisterController {

    private final StaffUserService staffUserService;

    private final StaffUserRepository staffUserRepository;

    private final Validator validator;

    private final StaffUserMapper staffUserMapper;

    public AdminRegisterController(StaffUserService staffUserService, StaffUserRepository staffUserRepository, Validator validator, StaffUserMapper staffUserMapper) {
        this.staffUserService = staffUserService;
        this.staffUserRepository = staffUserRepository;
        this.validator = validator;
        this.staffUserMapper = staffUserMapper;
    }

    @GetMapping("/admin_register_view.do")
    public String adminRegisterView(ModelMap model) {

        long users = staffUserRepository.count();

        if (users == 0) {
            model.addAttribute("user", new StaffUser());
            return "page/users/adminRegister";
        } else {
            return "redirect:/";
        }
    }

    @PostMapping("/admin_register.do")
    public String adminRegister(@ModelAttribute("user") UserRegisterDTO user,
                                BindingResult bindingResult,
                                ModelMap model) {

        if (user == null) {
            return "redirect:/admin_register_view.do";
        }

        validator.validate(user, bindingResult);

        if (bindingResult.hasErrors()) {
            model.addAttribute("user", user);
            return "page/users/adminRegister";
        }

        StaffUser newUser = staffUserMapper.map(user);
        newUser.setUserSecurity("ROLE_ADMIN");
        staffUserService.create(newUser);
        return "redirect:/login";
    }
}
