package com.micer.easyball.exception;

import com.micer.easyball.pojo.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;

@Component
@ControllerAdvice
public class AuditResponseAdvice implements ResponseBodyAdvice<Object> {

    private static final Logger logger = LoggerFactory.getLogger(AuditResponseAdvice.class);

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResponseResult) {
            ResponseResult<?> rr = (ResponseResult<?>) body;
            Integer status = rr.getStatus();
            if (status != null && (status == 403 || status == 410)) {
                String path = "unknown";
                String userId = "anonymous";
                ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attrs != null) {
                    HttpServletRequest servletRequest = attrs.getRequest();
                    path = servletRequest.getRequestURI();
                }
                try {
                    // try to read SecurityContextHolder safely
                    org.springframework.security.authentication.UsernamePasswordAuthenticationToken authentication =
                            (org.springframework.security.authentication.UsernamePasswordAuthenticationToken) org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
                    if (authentication != null && authentication.getPrincipal() instanceof com.micer.easyball.pojo.LoginUser) {
                        com.micer.easyball.pojo.LoginUser loginUser = (com.micer.easyball.pojo.LoginUser) authentication.getPrincipal();
                        userId = loginUser.getUser().getId();
                    }
                } catch (Exception ignored) {}

                logger.warn("AUDIT: unauthorized attempt - userId={}, path={}, status={}, time={}", userId, path, status, Instant.now().toString());
            }
        }
        return body;
    }
}
