package com.pandoli365.bibimbap.controller;

import com.pandoli365.bibimbap.mapper.GamesMapper;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

//이곳에서는 뷰만 제어
@Controller
public class WebMvcController implements WebMvcConfigurer, ErrorController {

    private final GamesMapper gamesMapper;

    public WebMvcController(GamesMapper gamesMapper) {
        this.gamesMapper = gamesMapper;
    }

    @RequestMapping("/error")
    public ModelAndView errorView(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("errer");
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if (status != null) {
            mv.addObject("statusCode", status);
        }
        return mv;
    }

    /* ✅ 허용된 페이지 목록 */
    private static final List<String> ALLOWED_PAGES = Arrays.asList(
            "error", "login", "profile", "signup", "terms", "operation-policy", ""
    );

    @GetMapping("/game/new")
    public ModelAndView gameRegisterView(HttpSession session) {
        if (!isLoggedIn(session)) {
            return new ModelAndView("redirect:/login");
        }
        return new ModelAndView("game-register");
    }

    @GetMapping("/")
    public ModelAndView indexView(@RequestParam(name = "q", required = false) String query) {
        return indexModelAndView(query);
    }

    @GetMapping("/{pageName}")
    public ModelAndView mainView(@PathVariable("pageName") String pageName,
                                 @RequestParam(name = "id", required = false) String id,
                                 @RequestParam(name = "q", required = false) String query,
                                 HttpSession session,
                                 HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        if (!ALLOWED_PAGES.contains(pageName)) {
            return new ModelAndView("redirect:/error");
        }
        switch (pageName) {
            case "error":
                mv.setViewName("errer");
                Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
                if (status != null) {
                    mv.addObject("statusCode", status);
                }
                break;
            case "login":
                if (isLoggedIn(session)) {
                    return new ModelAndView("redirect:/profile");
                }
                mv.setViewName("login");
                break;
            case "profile":
                if (!isLoggedIn(session)) {
                    return new ModelAndView("redirect:/login");
                }
                mv.addObject("myGames", gamesMapper.getGamesByUserId(sessionUserId(session)));
                mv.setViewName("profile");
                break;
            case "signup":
                mv.setViewName("signup");
                break;
            case "terms":
                mv.setViewName("terms");
                break;
            case "operation-policy":
                mv.setViewName("operation-policy");
                break;
            default:
                return indexModelAndView(query);
        }

        return mv;
    }

    private ModelAndView indexModelAndView(String query) {
        String normalizedQuery = query == null ? "" : query.trim();
        ModelAndView mv = new ModelAndView("index");
        mv.addObject("games", normalizedQuery.isBlank()
                ? gamesMapper.getVisibleGames()
                : gamesMapper.searchVisibleGames(normalizedQuery));
        mv.addObject("searchQuery", normalizedQuery);
        return mv;
    }

    private boolean isLoggedIn(HttpSession session) {
        return session != null && session.getAttribute("userId") != null;
    }

    private long sessionUserId(HttpSession session) {
        Object userId = session.getAttribute("userId");
        if (userId instanceof Number) {
            return ((Number) userId).longValue();
        }
        if (userId instanceof String) {
            return Long.parseLong((String) userId);
        }
        throw new IllegalStateException("로그인 세션에 사용자 ID가 없습니다.");
    }

    /// 접속기기 모바일 확인 함수
    private boolean isMobileDevice(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) {
            return false; // User-Agent가 없는 경우 기본값은 false
        }

        // 모바일 User-Agent 리스트 (대표적인 기기들)
        String[] mobileKeywords = {"Android", "iPhone", "iPad", "iPod", "Windows Phone", "Mobile", "Opera Mini", "BlackBerry"};

        // User-Agent 문자열이 모바일 기기를 포함하는지 검사
        return Arrays.stream(mobileKeywords).anyMatch(userAgent::contains);
    }
}
