package com.utic.center.utic.ptis.server.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jetbrains.annotations.NotNull;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

@Slf4j
@ToString
@Configuration
@RequiredArgsConstructor
@MapperScan(
        basePackages="com.utic.center.utic.ptis.server.dao.mapper.utic",
        sqlSessionFactoryRef = "uticSqlSessionFactory")
@EnableTransactionManagement
public class DatabaseUticConfig {

    private final ApplicationConfig config;

    @Value("${spring.datasource.hikari.utic.mapper-locations:classpath:mybatis/mapper/utic/**/*.xml}")
    String mapperLocations;

    @Value("${spring.datasource.hikari.utic.jdbc-url}")
    String jdbcUrl;

    @PostConstruct
    private void init() {
        if (this.mapperLocations.trim().isEmpty()) {
            this.mapperLocations = "classpath:mybatis/mapper/utic/**/*.xml";
        }
        log.info("utic:        jdbcUrl: {}", this.jdbcUrl);
        log.info("utic: mapperLocations: {}", this.mapperLocations);
    }

    @Bean(name="uticDataSource")
    @ConfigurationProperties(prefix="spring.datasource.hikari.utic")
    public DataSource uticDataSource() {
        HikariDataSource dataSource = DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .build();

        // 커넥션 초기화 SQL 설정 (Oracle 세션에 MODULE, ACTION 기록)
        if (this.jdbcUrl != null && this.jdbcUrl.toLowerCase().contains("oracle")) {
            String initSql = getString();
            dataSource.setConnectionInitSql(initSql);
        }
        return dataSource;
    }

    private @NotNull String getString() {
        final String moduleName = this.config.getProcessName();
        final String actionName = "Transfer ITS to PTIS";
        final String connInitSql;
        connInitSql = String.format(
                "BEGIN DBMS_APPLICATION_INFO.SET_MODULE('%s', '%s'); END;",
                moduleName, actionName
        );
        return connInitSql;
    }

    @Bean({"uticSqlSessionFactory"})
    public SqlSessionFactory uticSqlSessionFactory(@Autowired @Qualifier("uticDataSource") DataSource dataSource, ApplicationContext applicationContext)
            throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(applicationContext.getResources(this.mapperLocations));
        return factoryBean.getObject();
    }

    @Bean(name="uticSqlSession")
    public SqlSessionTemplate uticSqlSession(@Autowired @Qualifier("uticSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name="uticSqlSessionTemplate")
    public SqlSessionTemplate uticSqlSessionTemplate(
            @Autowired @Qualifier("uticSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name="uticTransactionManager")
    public DataSourceTransactionManager uticTransactionManager(@Autowired @Qualifier("uticDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
