package kr.iotdoor.boot.web;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AuthController {

    @GetMapping("/comn/user/login/login.do")
    public String loginRedirect() {
        return "redirect:/comn/user/login/loginUser.do";
    }

    @GetMapping("/comn/user/login/loginUser.do")
    public String loginPage(
        @RequestParam(name = "login_error", required = false) String loginError,
        Authentication authentication,
        HttpServletRequest request,
        Model model
    ) {
        if (authentication != null
            && authentication.isAuthenticated()
            && !(authentication instanceof AnonymousAuthenticationToken)) {
            return "redirect:/mfuc/index.do";
        }

        if (loginError != null) {
            model.addAttribute("loginMessage", "아이디 또는 비밀번호를 확인해주세요.");
        }

        String referer = request.getHeader("referer");
        model.addAttribute("returnUrl", referer == null ? "/" : referer);
        return "kr/iotdoor/comn/user/login/lgnPge";
    }
}
