package cn.iocoder.foodnexus.module.system.aspect;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author : yanghao
 * create at:  2025/11/18  13:57
 * @description:
 */
@Component
public class GlobalCookieSecurityFilter implements Filter {

    private static final String HTTP_ONLY = "HttpOnly";
    private static final String SECURE = "Secure";
    private static final String SAME_SITE = "SameSite=Strict"; // 可按需改为 Lax

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletResponse httpResp = (HttpServletResponse) response;

        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(httpResp) {

            @Override
            public void addHeader(String name, String value) {

                if ("Set-Cookie".equalsIgnoreCase(name)) {
                    String lower = value.toLowerCase();

                    // HttpOnly
                    if (!lower.contains("httponly")) {
                        value += "; " + HTTP_ONLY;
                    }

                    // Secure（仅在 HTTPS 生效）
                    if (!lower.contains("secure")) {
                        value += "; " + SECURE;
                    }

                    // SameSite
                    if (!lower.contains("samesite")) {
                        value += "; " + SAME_SITE;
                    }
                }

                super.addHeader(name, value);
            }
        };

        chain.doFilter(request, wrapper);
    }
}
