package com.yaoyuan.jiscuss.controller;

import com.yaoyuan.jiscuss.entity.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;

/**
 * Base controller exposing helpers shared by web controllers.
 *
 * @author Chuyaoyuan
 */
public class BaseController {

    /**
     * Returns the current authenticated user, or {@code null} when not logged in.
     */
    protected UserInfo getUserInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return null;
        }
        Object ctx = session.getAttribute("SPRING_SECURITY_CONTEXT");
        if (!(ctx instanceof SecurityContext securityContext)) {
            return null;
        }
        Authentication authentication = securityContext.getAuthentication();
        if (authentication == null || !(authentication.getPrincipal() instanceof UserInfo userInfo)) {
            return null;
        }
        return userInfo;
    }
}
