package com.storycove.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Base service class that provides library-aware database access.
 * 
 * This approach is safer than routing at the datasource level because:
 * 1. It doesn't interfere with Spring's initialization process
 * 2. It allows fine-grained control over which operations are library-aware
 * 3. It provides clear separation between authentication (uses default DB) and library operations
 */
@Component
public class LibraryAwareService {
    
    @Autowired
    private LibraryService libraryService;
    
    @Autowired
    @Qualifier("dataSource")
    private DataSource defaultDataSource;
    
    /**
     * Get a database connection for the current active library.
     * Falls back to default datasource if no library is active.
     */
    public Connection getCurrentLibraryConnection() throws SQLException {
        try {
            // Try to get library-specific connection
            DataSource libraryDataSource = libraryService.getCurrentDataSource();
            return libraryDataSource.getConnection();
        } catch (IllegalStateException e) {
            // No active library - use default datasource
            return defaultDataSource.getConnection();
        }
    }
    
    /**
     * Get a database connection for the default/fallback database.
     * Use this for authentication and system-level operations.
     */
    public Connection getDefaultConnection() throws SQLException {
        return defaultDataSource.getConnection();
    }
    
    /**
     * Check if a library is currently active
     */
    public boolean hasActiveLibrary() {
        try {
            return libraryService.getCurrentLibraryId() != null;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * Get the current active library ID, or null if none
     */
    public String getCurrentLibraryId() {
        try {
            return libraryService.getCurrentLibraryId();
        } catch (Exception e) {
            return null;
        }
    }
}