package com.printhub.printhub.controller.configuration;

import com.printhub.printhub.service.configuration.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import com.printhub.printhub.entity.configuration.User;
import com.printhub.printhub.repository.configuration.UserRepository;

@Controller
public class AuthController {

    private UserService userService;
    private UserRepository userRepository;

    @Autowired
    public AuthController(UserRepository userRepository, UserService userService) {
        this.userRepository = userRepository;
        this.userService = userService;
    }

    @PostMapping("/register")
    public String register(@RequestParam String username,
            @RequestParam String password,
            @RequestParam(defaultValue = "USER") String role) {
        userService.register(username, password, role);
        return "Usuario registrado correctamente.";
    }

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

    @ModelAttribute("currentUser")
    public User currentUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof org.springframework.security.core.userdetails.User springUser) {
            return userRepository.findByUsername(springUser.getUsername())
                    .orElse(null);
        }

        return null;
    }
}
