package com.saas.shared.interceptor;

import com.saas.admin.service.TenantSchemaMigrationService;
import com.saas.shared.core.TenantContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class TenantMigrationInterceptor implements HandlerInterceptor {
    
    @Autowired
    private TenantSchemaMigrationService migrationService;
    
    private final Set<String> checkedTenants = ConcurrentHashMap.newKeySet();
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String tenantId = TenantContext.getTenantId();
        
        if (tenantId != null && !tenantId.equals("admin") && !checkedTenants.contains(tenantId)) {
            try {
                log.debug("Checking schema migration for tenant: {}", tenantId);
                migrationService.migrateIfNeeded(tenantId);
                
                checkedTenants.add(tenantId);
                
            } catch (Exception e) {
                log.error("Failed to check/migrate schema for tenant: {}", tenantId, e);
            }
        }
        
        return true;
    }
    
    public void clearMigrationCache() {
        checkedTenants.clear();
        log.info("Migration check cache cleared. All tenants will be re-checked on next request.");
    }
    
    public void clearTenantFromCache(String tenantId) {
        checkedTenants.remove(tenantId);
        log.info("Tenant '{}' removed from migration cache. Will be re-checked on next request.", tenantId);
    }
}
