package com.mvrent.carrental.controller;

import com.mvrent.carrental.model.CategoryType;
import com.mvrent.carrental.model.Role;
import com.mvrent.carrental.model.User;
import com.mvrent.carrental.service.ConfigService;
import com.mvrent.carrental.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;
    private final ConfigService configService;

    @GetMapping("/login")
    public String login() {
        return "auth/login";
    }

    @GetMapping("/register")
    public String registerForm(Model model) {
        if (!model.containsAttribute("user")) {
            model.addAttribute("user", new User());
        }
        model.addAttribute("customerCategories", configService.categoriesOfType(CategoryType.CUSTOMER));
        return "auth/register";
    }

    @PostMapping("/register")
    public String register(@Valid @ModelAttribute("user") User user,
                           BindingResult result,
                           @RequestParam String rawPassword,
                           @RequestParam(required = false) Long customerCategoryId,
                           RedirectAttributes ra,
                           Model model) {
        if (result.hasErrors()) {
            model.addAttribute("customerCategories", configService.categoriesOfType(CategoryType.CUSTOMER));
            return "auth/register";
        }
        try {
            user.setRole(Role.CUSTOMER);
            user.setCustomerCategory(configService.findCategory(customerCategoryId));
            userService.register(user, rawPassword);
            ra.addFlashAttribute("success", "Account created — please log in");
            return "redirect:/login";
        } catch (IllegalArgumentException ex) {
            model.addAttribute("customerCategories", configService.categoriesOfType(CategoryType.CUSTOMER));
            model.addAttribute("error", ex.getMessage());
            return "auth/register";
        }
    }
}
