package com.storycove.config;

import com.storycove.service.LibraryService;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * Database configuration that sets up library-aware datasource routing.
 * 
 * This configuration replaces the default Spring Boot datasource with a routing
 * datasource that automatically directs all database operations to the appropriate
 * library-specific database based on the current active library.
 */
@Configuration
public class DatabaseConfig {
    
    @Value("${spring.datasource.url}")
    private String baseDbUrl;
    
    @Value("${spring.datasource.username}")
    private String dbUsername;
    
    @Value("${spring.datasource.password}")
    private String dbPassword;
    
    /**
     * Create a fallback datasource for when no library is active.
     * This connects to the main database specified in application.yml.
     */
    @Bean(name = "fallbackDataSource")
    public DataSource fallbackDataSource() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(baseDbUrl);
        config.setUsername(dbUsername);
        config.setPassword(dbPassword);
        config.setDriverClassName("org.postgresql.Driver");
        config.setMaximumPoolSize(10);
        config.setConnectionTimeout(30000);
        
        return new HikariDataSource(config);
    }
    
    /**
     * Primary datasource bean - uses smart routing that excludes authentication operations
     */
    @Bean(name = "dataSource")
    @Primary
    @DependsOn("libraryService")
    public DataSource primaryDataSource(LibraryService libraryService) {
        SmartRoutingDataSource routingDataSource = new SmartRoutingDataSource(
            libraryService, baseDbUrl, dbUsername, dbPassword);
        routingDataSource.setDefaultTargetDataSource(fallbackDataSource());
        routingDataSource.setTargetDataSources(new java.util.HashMap<>());
        return routingDataSource;
    }
    
}