package com.alterdekim.hearthhack.controller;

import com.alterdekim.hearthhack.dto.UserDTO;
import com.alterdekim.hearthhack.entity.User;
import com.alterdekim.hearthhack.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
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;

@Controller
public class AuthController {

    private final String base_title = " | Hearthhack";

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String loginPage(Model model) {
        model.addAttribute("title", "Login" + base_title);
        return "login";
    }

    @GetMapping("/signup")
    public String showRegistrationForm(Model model) {
        UserDTO userDto = new UserDTO();
        model.addAttribute("title", "Signup" + base_title);
        model.addAttribute("user", userDto);
        return "signup";
    }

    @PostMapping("/signup")
    public String registration(
            @ModelAttribute("user") @Valid UserDTO userDto,
            BindingResult result,
            Model model) {
        User existingUser = userService.findByUsername(userDto.getUsername());

        if(existingUser != null && existingUser.getUsername() != null && !existingUser.getUsername().isEmpty() ){
            result.rejectValue("username", null,
                    "There is already an account registered with the same username");
            return "redirect:/signup?error=already_exists";
        }

        if(result.hasErrors()) {
            model.addAttribute("user", new UserDTO());
            return "redirect:/signup?error=other";
        }

        userService.saveUser(userDto);
        return "redirect:/";
    }
}
