package com.alterdekim.hearthhack.controller;

import com.alterdekim.hearthhack.entity.User;
import com.alterdekim.hearthhack.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Slf4j
@Controller
public class AdminController {
    @Autowired
    private UserService userService;

    @GetMapping("/panel")
    public String adminPanel(Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if( authentication.isAuthenticated() ) {
            try {
                User u = userService.findByUsername(((org.springframework.security.core.userdetails.User) authentication.getPrincipal()).getUsername());
                if( !u.getRoles().get(0).getName().equals("ROLE_ADMIN") ) {
                    return "redirect:/";
                }
                return "panel";
            } catch (Exception e) {
                 log.error(e.getMessage(), e);
            }
        }
        return "redirect:/";
    }
}
