package com.storycove.config;

import com.storycove.service.LibraryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * Custom DataSource router that dynamically routes database calls to the appropriate 
 * library-specific datasource based on the current active library.
 * 
 * This makes ALL Spring Data JPA repositories automatically library-aware without 
 * requiring changes to existing repository or service code.
 */
public class LibraryAwareDataSource extends AbstractRoutingDataSource {
    
    private static final Logger logger = LoggerFactory.getLogger(LibraryAwareDataSource.class);
    
    private final LibraryService libraryService;
    
    public LibraryAwareDataSource(LibraryService libraryService) {
        this.libraryService = libraryService;
        // Set empty target datasources to satisfy AbstractRoutingDataSource requirements
        // We override determineTargetDataSource() so this won't be used
        setTargetDataSources(new java.util.HashMap<>());
    }
    
    @Override
    protected Object determineCurrentLookupKey() {
        String currentLibraryId = libraryService.getCurrentLibraryId();
        logger.debug("Routing database call to library: {}", currentLibraryId);
        return currentLibraryId;
    }
    
    @Override
    protected javax.sql.DataSource determineTargetDataSource() {
        try {
            // Check if LibraryService is properly initialized
            if (libraryService == null) {
                logger.debug("LibraryService not available, using default datasource");
                return getResolvedDefaultDataSource();
            }
            
            // Check if any library is currently active
            String currentLibraryId = libraryService.getCurrentLibraryId();
            if (currentLibraryId == null) {
                logger.debug("No active library, using default datasource");
                return getResolvedDefaultDataSource();
            }
            
            // Try to get the current library datasource
            javax.sql.DataSource libraryDataSource = libraryService.getCurrentDataSource();
            logger.debug("Successfully routing database call to library: {}", currentLibraryId);
            return libraryDataSource;
            
        } catch (IllegalStateException e) {
            // This is expected during authentication, startup, or when no library is active
            logger.debug("No active library (IllegalStateException) - using default datasource: {}", e.getMessage());
            return getResolvedDefaultDataSource();
        } catch (Exception e) {
            logger.warn("Unexpected error determining target datasource, falling back to default: {}", e.getMessage(), e);
            return getResolvedDefaultDataSource();
        }
    }
}