package net.siegeln.cameleer.saas.provisioning;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * Deletes tenant data from ClickHouse tables when a tenant is deleted
 * (GDPR data erasure). PostgreSQL cleanup is handled by TenantDatabaseService.
 */
@Service
public class TenantDataCleanupService {

    private static final Logger log = LoggerFactory.getLogger(TenantDataCleanupService.class);

    private final ProvisioningProperties props;

    public TenantDataCleanupService(ProvisioningProperties props) {
        this.props = props;
    }

    /**
     * Deletes tenant data from ClickHouse tables (GDPR data erasure).
     * PostgreSQL cleanup is handled by TenantDatabaseService.
     */
    public void cleanupClickHouse(String slug) {
        deleteClickHouseData(slug);
    }

    private void deleteClickHouseData(String slug) {
        String url = props.clickhouseUrl();
        if (url == null || url.isBlank()) {
            log.warn("No ClickHouse URL configured — skipping ClickHouse data cleanup");
            return;
        }

        try (Connection conn = DriverManager.getConnection(url, props.clickhouseUser(), props.clickhousePassword());
             Statement stmt = conn.createStatement()) {

            // Find all tables with a tenant_id column
            List<String> tables = new ArrayList<>();
            try (ResultSet rs = stmt.executeQuery(
                    "SELECT DISTINCT table FROM system.columns " +
                    "WHERE database = currentDatabase() AND name = 'tenant_id'")) {
                while (rs.next()) {
                    tables.add(rs.getString(1));
                }
            }

            for (String table : tables) {
                try {
                    stmt.execute("ALTER TABLE `" + table + "` DELETE WHERE tenant_id = '" + slug + "'");
                    log.info("Deleted ClickHouse data for tenant '{}' from table '{}'", slug, table);
                } catch (Exception e) {
                    log.warn("Failed to delete from ClickHouse table '{}' for tenant '{}': {}",
                            table, slug, e.getMessage());
                }
            }
        } catch (Exception e) {
            log.warn("Failed to clean up ClickHouse data for tenant '{}': {}", slug, e.getMessage());
        }
    }
}
