package ru.nbch.credit_tracker.component;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Slf4j
@Component
public class MapperTimingAspect {
    @Around("within(@org.apache.ibatis.annotations.Mapper *)")
    public Object timeMapper(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.nanoTime();
        try {
            return pjp.proceed();
        } finally {
            long tookMs = (System.nanoTime() - start) / 1_000_000;
            String method = pjp.getSignature().toShortString();
            if (tookMs > 1000) {
                log.warn("Slow mapper call {} took {} ms", method, tookMs);
            } else {
                log.debug("Mapper call {} took {} ms", method, tookMs);
            }
        }
    }
}
