package com.example.demo.entrysData.api;

import java.util.List;
import java.util.Objects;

import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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.RequestMapping;

import com.example.demo.core.configuration.Constants;
import com.example.demo.department.api.DepartmentDto;
import com.example.demo.department.service.DepartmentService;
import com.example.demo.entrysData.model.EntrysDataEntity;
import com.example.demo.entrysData.service.EntrysDataService;

import jakarta.validation.Valid;

@Controller
@RequestMapping(EntrysDataSignupController.URL)
public class EntrysDataSignupController {
    public static final String URL = "/signup";

    private static final String SIGNUP_VIEW = "signup";
    private static final String USER_ATTRIBUTE = "user";
    private static final String DEPARTMENT_ATTRIBUTE = "departments";

    private final DepartmentService departmentService;
    private final EntrysDataService userService;
    private final ModelMapper modelMapper;

    public EntrysDataSignupController(
            EntrysDataService userService,
            ModelMapper modelMapper, DepartmentService departmentService) {
        this.userService = userService;
        this.modelMapper = modelMapper;
        this.departmentService = departmentService;
    }

    private EntrysDataEntity toEntity(EntrysDataSignupDto dto) {
        final EntrysDataEntity entity = modelMapper.map(dto, EntrysDataEntity.class);
        entity.setDepartment(departmentService.get(dto.getDepartmentId()));
        return entity;
    }

    private List<DepartmentDto> getDepartments(){
       return modelMapper.map(departmentService.getAll(), new TypeToken<List<DepartmentDto>>(){}.getType());
    }

    @GetMapping
    public String getSignup(Model model) {
        model.addAttribute(USER_ATTRIBUTE, new EntrysDataSignupDto());
        model.addAttribute(DEPARTMENT_ATTRIBUTE, getDepartments());
        return SIGNUP_VIEW;
    }

    @PostMapping
    public String signup(
            @ModelAttribute(name = USER_ATTRIBUTE) @Valid EntrysDataSignupDto user,
            BindingResult bindingResult,
            Model model) {
        if (bindingResult.hasErrors()) {
            return SIGNUP_VIEW;
        }
        if (!Objects.equals(user.getPassword(), user.getPasswordConfirm())) {
            bindingResult.rejectValue("password", "signup:passwords", "Пароли не совпадают.");
            model.addAttribute(USER_ATTRIBUTE, user);
            return SIGNUP_VIEW;
        }
        userService.create(toEntity(user));
        return Constants.REDIRECT_VIEW + Constants.LOGIN_URL + "?signup";
    }
}
