package com.eactive.eai.rms.onl.common.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional
public class HttpLogTruncateService {
    public static String TABLE_HTTP_ADAPTER_EXTRA_HEADER = "http_adapter_extra_header";
    public static String TABLE_HTTP_ADAPTER_EXTRA_LOG = "http_adapter_extra_log";

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * DB 별 파티션 TRUNCATE 하는 쿼리 수행
     * MYSQL (일요일) 예시>
     * ALTER TABLE http_adapter_extra_header TRUNCATE PARTITION p1;
     * POSTGRESQL (일요일) 예시>
     * TRUNCATE TABLE http_adapter_extra_header_1;
     * @param targetDayOfWeekNumber
     */
    public void truncLogTable(String databaseType, String schema, int targetDayOfWeekNumber) {
        List<String> queries = new ArrayList<>();

        String partitionPrefix;
        switch (databaseType.toLowerCase()) {
            case "mysql":
                partitionPrefix = "p";
                queries.add(buildTruncateQueryForMysql(schema, TABLE_HTTP_ADAPTER_EXTRA_HEADER, partitionPrefix, targetDayOfWeekNumber));
                queries.add(buildTruncateQueryForMysql(schema, TABLE_HTTP_ADAPTER_EXTRA_LOG, partitionPrefix, targetDayOfWeekNumber));
                break;

            case "postgresql":
                partitionPrefix = TABLE_HTTP_ADAPTER_EXTRA_HEADER + "_";
                queries.add(buildTruncateQueryPostgreSQL(schema, partitionPrefix, targetDayOfWeekNumber));
                partitionPrefix = TABLE_HTTP_ADAPTER_EXTRA_LOG + "_";
                queries.add(buildTruncateQueryPostgreSQL(schema, partitionPrefix, targetDayOfWeekNumber));
                break;

            //TODO: 다른 데이터베이스 유형에 대한 처리 추가
            default:
                throw new UnsupportedOperationException("Database type not supported: " + databaseType);
        }

        // 쿼리 일괄 실행
        executeQueries(queries);
    }

    private String buildTruncateQueryForMysql(String schema, String tableName, String partitionPrefix, int partitionNumber) {
        return String.format("ALTER TABLE %s.%s TRUNCATE PARTITION %s%d", schema, tableName, partitionPrefix, partitionNumber);
    }

    private String buildTruncateQueryPostgreSQL(String schema, String partitionPrefix, int partitionNumber) {
        return String.format("TRUNCATE TABLE %s.%s%d", schema, partitionPrefix, partitionNumber);
    }

    private void executeQueries(List<String> queries) {
        for (String query : queries) {
            log.info("execute truncate - {}", query);
            entityManager.createNativeQuery(query).executeUpdate();
        }
    }
}
