package com.bonus.canteen.core.common.threadPool;

import com.bonus.canteen.core.common.utils.TenantContextHolder;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.task.TaskDecorator;

public class TenantTaskDecorator implements TaskDecorator {
   private static final Logger log = LoggerFactory.getLogger(TenantTaskDecorator.class);

   @Override
   public Runnable decorate(Runnable runnable) {
      Long tenantId = TenantContextHolder.getTenantId();
      return () -> {
         try {
            TenantContextHolder.setTenantId(tenantId);
            runnable.run();
         } finally {
            try {
               TenantContextHolder.clear();
               PageHelper.clearPage();
            } catch (Exception e) {
               log.error("Failed to clear tenant context or page helper", e);
            }
         }
      };
   }
}
