package top.tqx.demo_1.aspect;

import jakarta.servlet.http.HttpServletRequest;
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.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.tqx.demo_1.util.IpUtil;

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Pointcut("execution(* top.tqx.demo_1.controller..*(..))")
    public void controllerPointcut() {
    }

    @Around("controllerPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return joinPoint.proceed();
        }

        HttpServletRequest request = attributes.getRequest();

        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();

        log.info("请求 | URL: {} | 方法: {} | IP: {}", 
                request.getRequestURL(), 
                request.getMethod(),
                IpUtil.getIpAddress(request));

        try {
            Object result = joinPoint.proceed();
            long endTime = System.currentTimeMillis();

            log.info("响应 | 耗时: {}ms", endTime - startTime);

            return result;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.error("异常 | 消息: {} | 耗时: {}ms", e.getMessage(), endTime - startTime);
            throw e;
        }
    }
}
