package com.ytpm.question.aop;

import com.ytpm.question.config.datasource.DynamicDataSourceContextHolder;
import com.ytpm.app.enums.DataSourceType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(1)
public class DataSourceAspect {

    @Pointcut("execution(* com.ytpm.question.service.*.*(..))")
    public void servicePointcut() {}

    @Before("servicePointcut()")
    public void beforeService(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        if (methodName.startsWith("get") ||
            methodName.startsWith("find") ||
            methodName.startsWith("select") ||
            methodName.startsWith("query")) {
            DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE);
        } else {
            DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER);
        }
    }

    @After("servicePointcut()")
    public void afterService() {
        DynamicDataSourceContextHolder.clear();
    }
}
