package com.pandoli365.bibimbap.security;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class RbacInterceptor implements HandlerInterceptor {

    private final PermissionGate permissionGate;

    public RbacInterceptor(PermissionGate permissionGate) {
        this.permissionGate = permissionGate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws IOException {
        HttpSession session = request.getSession(false);
        boolean page = request.getRequestURI().endsWith("/admin/console");

        if (!permissionGate.isAuthenticated(session)) {
            if (page) {
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
            writeJson(response, 401, "로그인이 필요합니다.");
            return false;
        }

        if (!permissionGate.isAdmin(session)) {
            writeJson(response, 403, "권한이 없습니다.");
            return false;
        }

        return true;
    }

    private void writeJson(HttpServletResponse response, int status, String message) throws IOException {
        response.setStatus(status);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"status\":" + status + ",\"message\":\"" + message + "\"}");
    }
}
