"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReconciliationService = exports.ReconciliationType = void 0;
const api_client_1 = require("../api-client");
const config_storage_1 = require("../config-storage");
const cli_cluster_repository_1 = require("../repositories/cli-cluster.repository");
/**
 * Reconciliation service
 *
 * CA, Provider, VNet, Observability, Firewall are now seeded automatically
 * by BootstrapSeeder (NestJS OnModuleInit) reading from flui-secrets K8s Secret.
 * No HTTP reconciliation needed for those types.
 *
 * Only DNS remains here — it is API-driven (no data from CLI) and optional.
 */
var ReconciliationType;
(function (ReconciliationType) {
    ReconciliationType["DNS"] = "dns";
    ReconciliationType["ALL"] = "all";
})(ReconciliationType || (exports.ReconciliationType = ReconciliationType = {}));
class ReconciliationService {
    constructor(apiUrl) {
        this.configStorage = new config_storage_1.ConfigStorage();
        this.apiClient = new api_client_1.ApiClient({
            baseUrl: apiUrl,
            apiKey: this.configStorage.getApiKey(),
        });
        this.clusterRepository = new cli_cluster_repository_1.CliClusterRepository();
    }
    async reconcile(options = {}) {
        const types = options.types || [ReconciliationType.ALL];
        const results = [];
        const typesToRun = types.includes(ReconciliationType.ALL)
            ? [ReconciliationType.DNS]
            : types;
        for (const type of typesToRun) {
            try {
                let result;
                if (type === ReconciliationType.DNS) {
                    result = await this.reconcileDns(options);
                }
                else {
                    result = {
                        type,
                        success: false,
                        message: `Unknown reconciliation type: ${type}`,
                    };
                }
                results.push(result);
            }
            catch (error) {
                results.push({
                    type,
                    success: false,
                    message: `Reconciliation failed: ${error.message}`,
                    error: error.stack || error.message,
                });
            }
        }
        return { results, allSuccess: results.every((r) => r.success) };
    }
    /**
     * Trigger DNS reconciliation via API (API-driven, no data from CLI).
     * Optional — skipped silently if no DNS is configured.
     */
    async reconcileDns(options) {
        try {
            const cluster = await this.clusterRepository.findOne({
                where: { metadata: { isObservabilityCluster: true } },
            });
            if (!cluster) {
                return {
                    type: ReconciliationType.DNS,
                    success: true,
                    message: 'No observability cluster found, skipping DNS reconciliation',
                };
            }
            try {
                const dnsConfig = await this.apiClient.get(`/dns/cluster/${cluster.id}`);
                if (!dnsConfig) {
                    return {
                        type: ReconciliationType.DNS,
                        success: true,
                        message: 'No DNS configuration found for cluster, skipping',
                    };
                }
                await this.apiClient.post(`/dns/${dnsConfig.id}/reconcile`);
                return {
                    type: ReconciliationType.DNS,
                    success: true,
                    message: `DNS reconciliation triggered for ${dnsConfig.baseDomain}`,
                    details: {
                        baseDomain: dnsConfig.baseDomain,
                        dnsProvider: dnsConfig.dnsProvider,
                    },
                };
            }
            catch (apiError) {
                if (apiError.status === 404 || apiError.statusCode === 404) {
                    return {
                        type: ReconciliationType.DNS,
                        success: true,
                        message: 'No DNS configuration found for cluster, skipping',
                    };
                }
                throw apiError;
            }
        }
        catch (error) {
            return {
                type: ReconciliationType.DNS,
                success: false,
                message: `DNS reconciliation failed: ${error.message}`,
                error: error.stack || error.message,
            };
        }
    }
}
exports.ReconciliationService = ReconciliationService;
