package com.eactive.httpmockserver.client.service;

import com.eactive.httpmockserver.client.repository.ApiRequestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import javax.transaction.Transactional;
import java.sql.Connection;
import java.sql.Statement;


@Service
@Transactional
public class ApiRequestMigrationService {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    ApiRequestRepository apiRequestRepository;

    @EventListener(ApplicationReadyEvent.class)
    public void migrate() {
        // Fetch DataSource from Spring Context
        DataSource dataSource = applicationContext.getBean(DataSource.class);

        try (Connection connection = dataSource.getConnection()) {
            String sql1 = String.format("ALTER TABLE %s ALTER COLUMN %s %s;", "API_REQUEST_INFO", "HEADERS", "CLOB");
            try (Statement statement = connection.createStatement()) {
                statement.execute(sql1);
            }
            String sql2 = String.format("ALTER TABLE %s ALTER COLUMN %s %s;", "API_REQUEST_INFO", "QUERY_PARAMS", "CLOB");
            try (Statement statement = connection.createStatement()) {
                statement.execute(sql2);
            }
            String sql3 = String.format("ALTER TABLE %s ALTER COLUMN %s %s;", "API_REQUEST_INFO", "REQUEST_BODY", "CLOB");
            try (Statement statement = connection.createStatement()) {
                statement.execute(sql3);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        apiRequestRepository.findAll().forEach(apiRequest -> {

            apiRequest.setHeaders(apiRequest.getHeaders().replace("=", "::"));
            apiRequest.setQueryParams(apiRequest.getQueryParams().replace("=", "::"));

            apiRequestRepository.save(apiRequest);
        });

    }

}
