package at.procon.dip.search.repository;

import at.procon.dip.search.api.SearchExecutionContext;
import at.procon.dip.search.dto.SearchEngineType;
import at.procon.dip.search.dto.SearchHit;
import at.procon.dip.search.dto.SearchMatchField;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
@RequiredArgsConstructor
public class DocumentFullTextSearchRepositoryImpl implements DocumentFullTextSearchRepository {

    private final NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public List<SearchHit> search(SearchExecutionContext context, int limit) {
        String effectiveConfigExpr = effectiveConfigExpression("dtr");
        String tsQueryExpr = tsQueryExpression(effectiveConfigExpr);

        StringBuilder sql = new StringBuilder("""
                SELECT
                    d.id AS document_id,
                    dtr.id AS representation_id,
                    CAST(dtr.representation_type AS text) AS representation_type,
                    dtr.is_primary AS is_primary,
                    dtr.chunk_index AS chunk_index,
                    dtr.chunk_start_offset AS chunk_start_offset,
                    dtr.chunk_end_offset AS chunk_end_offset,
                    CAST(d.document_type AS text) AS document_type,
                    CAST(d.document_family AS text) AS document_family,
                    CAST(d.visibility AS text) AS visibility,
                    d.title AS title,
                    d.summary AS summary,
                    COALESCE(dtr.language_code, d.language_code) AS language_code,
                    d.mime_type AS mime_type,
                    d.created_at AS created_at,
                    d.updated_at AS updated_at,
                    ts_headline(
                        """
                ).append(effectiveConfigExpr).append("""
                        ,
                        COALESCE(dtr.text_body, ''),
                        """).append(tsQueryExpr).append("""
                        ,
                        'MaxFragments=2, MinWords=5, MaxWords=20'
                    ) AS snippet,
                    ranked.score AS score
                FROM (
                    SELECT
                        d.id AS document_id,
                        dtr.id AS representation_id,
                        ts_rank_cd(
                            dtr.search_vector,
                            """).append(tsQueryExpr).append("""
                        ) AS score,
                        d.updated_at AS updated_at
                    FROM doc.doc_text_representation dtr
                    JOIN doc.doc_document d ON d.id = dtr.document_id
                    LEFT JOIN doc.doc_tenant dt ON dt.id = d.owner_tenant_id
                    WHERE dtr.search_vector IS NOT NULL
                      AND dtr.search_vector @@ """).append(tsQueryExpr).append("""
                """);

        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("queryText", context.getRequest().getQueryText());

        SearchSqlFilterSupport.appendCommonFilters(sql, params, context, "d", "dtr", true);

        sql.append("""
                    ORDER BY score DESC, d.updated_at DESC
                    LIMIT :limit
                ) ranked
                JOIN doc.doc_text_representation dtr ON dtr.id = ranked.representation_id
                JOIN doc.doc_document d ON d.id = ranked.document_id
                ORDER BY ranked.score DESC, d.updated_at DESC
                """);
        params.addValue("limit", limit);

        return jdbcTemplate.query(
                sql.toString(),
                params,
                new SearchHitRowMapper(SearchEngineType.POSTGRES_FULLTEXT, SearchMatchField.REPRESENTATION_TEXT)
        );
    }

    private static String effectiveConfigExpression(String representationAlias) {
        return """
                CASE
                    WHEN NULLIF(%s.search_config, '') IS NULL THEN 'simple'::regconfig
                    ELSE %s.search_config::regconfig
                END
                """.formatted(representationAlias, representationAlias).trim();
    }

    private static String tsQueryExpression(String configExpression) {
        return """
                websearch_to_tsquery(
                    %s,
                    :queryText
                )
                """.formatted(configExpression).trim();
    }
}
