package at.procon.dip.testsupport;

import at.procon.dip.FixedPortPostgreSQLContainer;
import at.procon.dip.domain.document.repository.DocumentRepository;
import at.procon.dip.domain.document.repository.DocumentTextRepresentationRepository;
import at.procon.dip.domain.ted.repository.TedNoticeProjectionRepository;
import at.procon.ted.repository.ProcurementDocumentRepository;
import javax.sql.DataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

@SpringBootTest(classes = TedStructuredSearchTestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@Testcontainers
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestPropertySource(properties = {
        "spring.jpa.hibernate.ddl-auto=create-drop",
        "spring.jpa.show-sql=false",
        "spring.jpa.open-in-view=false",
        "spring.jpa.properties.hibernate.default_schema=doc",
        "spring.main.lazy-initialization=true",
        "dip.runtime.mode=NEW",
        "dip.search.default-page-size=20",
        "dip.search.max-page-size=100",
        "dip.search.fulltext-weight=0.60",
        "dip.search.trigram-weight=0.40",
        "dip.search.semantic-weight=0.45",
        "dip.search.recency-boost-weight=0.05",
        "dip.search.trigram-similarity-threshold=0.10",
        "server.servlet.context-path=/api"
})
public abstract class AbstractTedStructuredSearchIntegrationTest {

    private static final int HOST_PORT = 15434;
    private static final String DB_NAME = "dip_ted_search_test";
    private static final String DB_USER = "test";
    private static final String DB_PASSWORD = "test";
    private static final String JDBC_URL = "jdbc:postgresql://localhost:" + HOST_PORT + "/" + DB_NAME;

    @Container
    static PostgreSQLContainer<?> postgres = new FixedPortPostgreSQLContainer<>("postgres:16-alpine", HOST_PORT)
            .withDatabaseName(DB_NAME)
            .withUsername(DB_USER)
            .withPassword(DB_PASSWORD)
            .withInitScript("sql/create-doc-search-test-schemas.sql");

    @DynamicPropertySource
    static void registerProperties(DynamicPropertyRegistry registry) {
        if (!postgres.isRunning()) {
            postgres.start();
        }
        registry.add("spring.datasource.url", () -> JDBC_URL);
        registry.add("spring.datasource.username", () -> DB_USER);
        registry.add("spring.datasource.password", () -> DB_PASSWORD);
        registry.add("spring.datasource.driver-class-name", () -> "org.postgresql.Driver");
    }

    @Autowired protected JdbcTemplate jdbcTemplate;
    @Autowired protected DataSource dataSource;
    @Autowired protected MockMvc mockMvc;
    @Autowired protected SearchTestDataFactory dataFactory;
    @Autowired protected DocumentRepository documentRepository;
    @Autowired protected DocumentTextRepresentationRepository representationRepository;
    @Autowired protected TedNoticeProjectionRepository tedNoticeProjectionRepository;
    @Autowired protected ProcurementDocumentRepository procurementDocumentRepository;

    @BeforeEach
    void resetDatabase() {
        ensureSearchColumnsAndIndexes();
        cleanupDatabase();
    }

    protected void ensureSearchColumnsAndIndexes() {
        jdbcTemplate.execute("CREATE SCHEMA IF NOT EXISTS doc");
        jdbcTemplate.execute("CREATE SCHEMA IF NOT EXISTS ted");
        jdbcTemplate.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm with schema doc");
        jdbcTemplate.execute("ALTER TABLE doc.doc_text_representation ADD COLUMN IF NOT EXISTS search_config VARCHAR(64)");
        jdbcTemplate.execute("ALTER TABLE doc.doc_text_representation ADD COLUMN IF NOT EXISTS search_vector tsvector");
        jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_doc_text_repr_search_vector_test ON doc.doc_text_representation USING GIN (search_vector)");
        jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_doc_document_title_trgm_test ON doc.doc_document USING GIN (title doc.gin_trgm_ops)");
        jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_doc_document_summary_trgm_test ON doc.doc_document USING GIN (summary doc.gin_trgm_ops)");
        jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_doc_text_repr_text_trgm_test ON doc.doc_text_representation USING GIN (text_body doc.gin_trgm_ops)");
    }

    protected void cleanupDatabase() {
        jdbcTemplate.execute("TRUNCATE TABLE ted.ted_notice_organization, ted.ted_notice_lot, ted.ted_notice_projection, doc.doc_text_representation, doc.doc_document, doc.doc_tenant, doc.procurement_lot, doc.organization, doc.procurement_document RESTART IDENTITY CASCADE");
    }
}
