package com.agileboot.common.web.aspect;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.stream.Collectors;

@Aspect
@Slf4j
@Component
public class LogAspect {

    @Value("${agileboot.traceRequestIdKey:W-RequestId}")
    private String requestIdKey;

    @Pointcut("execution(* *..controller..*.*(..))")
    public void logPointCut() {
    }


    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            log.warn("无法获取请求上下文信息");
            return point.proceed();
        }

        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();

        String url = request.getRequestURI().toString();
        String uuid = response != null ? response.getHeader(requestIdKey) : null;

        Object[] args = point.getArgs();
        String reqParam = filterAndConvertArgsToString(args);

        log.info("request start, path: {}, uuid: {}, params: {}", url, uuid, reqParam);

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        try {
            Object res = point.proceed();
            stopWatch.stop();
            long totalTimeMillis = stopWatch.getTotalTimeMillis();
            log.info("request end, path: {}, uuid: {}, cost: {}ms", url, uuid, totalTimeMillis);
            return res;
        } catch (Throwable throwable) {
            stopWatch.stop();
            long totalTimeMillis = stopWatch.getTotalTimeMillis();
            log.error("request error, path: {}, uuid: {}, cost: {}ms", url, uuid, totalTimeMillis);
            throw throwable;
        }
    }

    private String filterAndConvertArgsToString(Object[] args) {
        if (args == null || args.length == 0) {
            return "";
        }

        return Arrays.stream(args)
                .filter(arg -> !(arg instanceof HttpServletRequest ||
                        arg instanceof HttpServletResponse ||
                        arg instanceof MultipartFile ||
                        (arg != null && arg.getClass().isArray() && arg.getClass().getComponentType() != null &&
                                arg.getClass().getComponentType().isAssignableFrom(MultipartFile.class))))
                .map(String::valueOf)
                .collect(Collectors.joining(", ", "[", "]"));
    }

}
