package fr.titionfire.ffsaf.data;

import org.hibernate.boot.model.FunctionContributions;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.query.sqm.function.SqmFunctionRegistry;
import org.hibernate.query.sqm.produce.function.FunctionParameterType;
import org.hibernate.type.BasicType;
import org.hibernate.type.BasicTypeRegistry;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.spi.TypeConfiguration;
import org.jboss.logging.Logger;

public class CustomPostgreSQLDialect extends PostgreSQLDialect {
    private static final Logger LOGGER = Logger.getLogger(PostgreSQLDialect.class);

    public CustomPostgreSQLDialect() {
        super();
    }

    @Override
    public void initializeFunctionRegistry(FunctionContributions functionContributions) {
        super.initializeFunctionRegistry(functionContributions);

        LOGGER.info("Initializing custom function registry");

        SqmFunctionRegistry functionRegistry = functionContributions.getFunctionRegistry();
        TypeConfiguration typeConfiguration = functionContributions.getTypeConfiguration();
        BasicTypeRegistry basicTypeRegistry = typeConfiguration.getBasicTypeRegistry();
        BasicType<String> stringType = basicTypeRegistry.resolve(StandardBasicTypes.STRING);

        functionRegistry.namedDescriptorBuilder("unaccent").setInvariantType(stringType).setExactArgumentCount(1)
                .setParameterTypes(new FunctionParameterType[]{FunctionParameterType.STRING}).register();

    }
}