package ru.nbch.credit_tracker.config.datasource;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import ru.nbch.credit_tracker.config.settings.CreditTrackerSettings;

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

@Slf4j
@Configuration
@MapperScan(
        basePackages = "ru.nbch.credit_tracker.mapper.scoring",
        sqlSessionFactoryRef = "sqlSessionScoring"
)
public class ScoringDataSourceConfig extends DatabaseConfig {

    @Value("classpath:mybatis/mapper/scoring/*.xml")
    private Resource[] resources;

    @Bean(name = "scoringDataSource")
    public DataSource dataSource(CreditTrackerSettings config) throws SQLException {
        DataSource dataSource = createDataSource(config.getScoringDataSourceSettings());
        try (Connection connection = dataSource.getConnection()) {
            connection.isValid(3);
        } catch (SQLException e) {
            log.error("Unable to connect to Scoring url={}", config.getScoringDataSourceSettings().url(), e);
            throw e;
        }
        log.info("Connected to Scoring: url={}", config.getScoringDataSourceSettings().url());
        return dataSource;
    }

    @Bean(name = "sqlSessionScoring")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("scoringDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(resources);
        return sqlSessionFactoryBean.getObject();
    }
}
