package com.atlassian.stash.internal.hibernate;

import com.atlassian.hibernate.extras.hql.JoinTemporaryTableBulkIdStrategy;
import com.atlassian.stash.internal.db.DbType;
import com.atlassian.stash.internal.jdbc.DataSourceConfiguration;
import org.hibernate.cfg.AvailableSettings;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;

import javax.sql.DataSource;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class ExtendedLocalSessionFactoryBeanTest {

    @Mock
    private DataSource dataSource;

    @Mock
    private DataSourceConfiguration dataSourceConfiguration;

    @InjectMocks
    private ExtendedLocalSessionFactoryBean localSessionFactoryBean;

    @Test
    public void shouldInjectCustomMultiTableBulkStrategyForMySql() {
        when(dataSourceConfiguration.getDriverClassName()).thenReturn(DbType.MYSQL.getDriverClassName());
        LocalSessionFactoryBuilder configuration = new LocalSessionFactoryBuilder(dataSource);

        localSessionFactoryBean.customizeConfiguration(configuration);

        assertEquals(configuration.getProperty(AvailableSettings.HQL_BULK_ID_STRATEGY),
                JoinTemporaryTableBulkIdStrategy.class.getName());
    }

    @Test
    public void shouldUseDefaultHibernateMultiTableBulkIdStrategyForNonMySqlDatabases() {
        for (DbType type : DbType.values()) {
            if (type == DbType.MYSQL) {
                continue;
            }

            when(dataSourceConfiguration.getDriverClassName()).thenReturn(type.getDriverClassName());
            LocalSessionFactoryBuilder configuration = new LocalSessionFactoryBuilder(dataSource);

            localSessionFactoryBean.customizeConfiguration(configuration);

            // make sure we don't provide our custom strategy implementation
            assertNotEquals(configuration.getProperty(AvailableSettings.HQL_BULK_ID_STRATEGY),
                    JoinTemporaryTableBulkIdStrategy.class.getName());
        }
    }
}
