/*-
 * ~~~~~~licensing~~~~~~
 * system-commons
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.common.aggregation.repo;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * PostgreSQL specific {@link JdbcAggregationRepository} that deals with SQL Violation Exceptions using special
 * {@code INSERT INTO .. ON CONFLICT DO NOTHING} claues.
 */
public class PostgresAggregationRepository extends JdbcAggregationRepository {

    /**
     * Creates an aggregation repository
     */
    public PostgresAggregationRepository() {
    }

    /**
     * Creates an aggregation repository with the three mandatory parameters
     */
    public PostgresAggregationRepository(PlatformTransactionManager transactionManager, String repositoryName,
                                         DataSource dataSource) {
        super(transactionManager, repositoryName, dataSource);
    }

    /**
     * Inserts a new record into the given repository table
     *
     * @param camelContext   the current CamelContext
     * @param correlationId  the correlation key
     * @param exchange       the aggregated exchange
     * @param repositoryName The name of the table
     */
    protected void insert(
            final CamelContext camelContext, final String correlationId, final Exchange exchange, String repositoryName)
            throws Exception {
        // The default totalParameterIndex is 2 for ID and Exchange. Depending on logic this will be increased
        int totalParameterIndex = 2;
        StringBuilder queryBuilder = new StringBuilder()
                .append("INSERT INTO ").append(repositoryName)
                .append('(')
                .append(EXCHANGE).append(", ")
                .append(ID);

        if (isStoreBodyAsText()) {
            queryBuilder.append(", ").append(BODY);
            totalParameterIndex++;
        }

        if (hasHeadersToStoreAsText()) {
            for (String headerName : getHeadersToStoreAsText()) {
                queryBuilder.append(", ").append(headerName);
                totalParameterIndex++;
            }
        }

        queryBuilder.append(") VALUES (");

        for (int i = 0; i < totalParameterIndex - 1; i++) {
            queryBuilder.append("?, ");
        }
        queryBuilder.append("?)");

        queryBuilder.append(" ON CONFLICT DO NOTHING");

        String sql = queryBuilder.toString();

        int updateCount = insertHelper(camelContext, correlationId, exchange, sql, 1L);
        if (updateCount == 0 && getRepositoryName().equals(repositoryName)) {
            throw new DataIntegrityViolationException("No row was inserted due to data violation");
        }
    }

}
