package io.netfoundry.billing.config;

import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

@TestConfiguration
public class EmbeddedDbTestConfig {

  @Primary
  @Bean
  public DataSource dataSource() {
    return DataSourceBuilder.create()
        .driverClassName("org.h2.Driver")
        .url("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS billing")
        .username("sa")
        .password("")
        .build();
  }

  @Bean(initMethod = "migrate")
  public Flyway flyway(DataSource dataSource) {
    return Flyway.configure()
        .dataSource(dataSource)
        .schemas("billing")
        .locations("classpath:database/testmigration")
        .load();
  }

  @Bean
  public JdbcTemplate plainJdbcTemplate(DataSource dataSource) {
    return new JdbcTemplate(dataSource);
  }
}
