package com.caliverse.admin.global.common.aspect;

import com.caliverse.admin.global.component.transaction.TransactionIdManager;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import static com.caliverse.admin.global.common.constants.CommonConstants.TRANSACTION_ID_KEY;

@Aspect
@Component
@RequiredArgsConstructor
public class TransactionIdAspect {
    private final TransactionIdManager transactionIdManager;

    @Around("@annotation(org.springframework.transaction.annotation.Transactional)")
    public Object setTransactionId(ProceedingJoinPoint joinPoint) throws Throwable {
        boolean isNewTransaction = !TransactionSynchronizationManager.hasResource(TRANSACTION_ID_KEY);

        if (isNewTransaction) {
            transactionIdManager.getCurrentTransactionId(); // 새로운 트랜잭션 ID 생성
        }

        try {
            return joinPoint.proceed();
        } finally {
            if (isNewTransaction) {
                TransactionSynchronizationManager.unbindResource(TRANSACTION_ID_KEY);
            }
        }
    }
}
