package io.delphiplatform.api.integration.container;

import org.testcontainers.containers.PostgreSQLContainer;

import io.delphiplatform.api.integration.util.EnvUtils;
import io.delphiplatform.api.utils.Constants;

public class DelphiPostgreSQLContainer extends PostgreSQLContainer<DelphiPostgreSQLContainer> {

    private static final String POSTGRES_IMAGE_NAME = "postgres:13.2";

    private static DelphiPostgreSQLContainer container;

    private DelphiPostgreSQLContainer() {
        super(POSTGRES_IMAGE_NAME);
    }

    public static DelphiPostgreSQLContainer getInstance() {
        if (container == null) {
            container = new DelphiPostgreSQLContainer()
                .withDatabaseName("delphi_main")
                .withUsername("postgres")
                .withPassword("postgres")
                .withInitScript(Constants.DB_MIGRATIONS_DIR + "/init/local.sql");
        }
        return container;
    }

    @Override
    public void start() {
        super.start();
        EnvUtils.setEnvVar("spring.datasource.url", container.getJdbcUrl());
        EnvUtils.setEnvVar("spring.datasource.username", container.getUsername());
        EnvUtils.setEnvVar("spring.datasource.password", container.getPassword());
    }

    @Override
    public void stop() {
        //container is needed through whole tests run lifecycle, will be stopped by testcontainers shutdown hooks
    }
}
