"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var ClusterFirewallIntegrationService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClusterFirewallIntegrationService = void 0;
const common_1 = require("@nestjs/common");
const firewall_desired_state_service_1 = require("../../firewalls/services/firewall-desired-state.service");
const firewall_reconciliation_service_1 = require("../../firewalls/services/firewall-reconciliation.service");
/**
 * Service to handle cluster-firewall integration
 * Manages firewall creation and deletion during cluster lifecycle
 */
let ClusterFirewallIntegrationService = ClusterFirewallIntegrationService_1 = class ClusterFirewallIntegrationService {
    constructor(firewallDesiredStateService, firewallReconciliationService) {
        this.firewallDesiredStateService = firewallDesiredStateService;
        this.firewallReconciliationService = firewallReconciliationService;
        this.logger = new common_1.Logger(ClusterFirewallIntegrationService_1.name);
    }
    /**
     * Create and reconcile firewall for a cluster
     * IMPORTANT: This MUST be called BEFORE creating any cluster nodes
     */
    async createAndReconcileFirewall(cluster, desiredRules) {
        this.logger.log(`Creating firewall for cluster ${cluster.id} (provider: ${cluster.provider}) with ${desiredRules.length} rules: ` +
            JSON.stringify(desiredRules.map((r) => `${r.direction}:${r.protocol}:${r.port}`)));
        try {
            // Create firewall with desired rules
            const firewall = await this.firewallDesiredStateService.createFirewall(cluster.id, desiredRules);
            this.logger.log(`Firewall DB record ${firewall.id} created for cluster ${cluster.id}, triggering provider reconciliation`);
            // Reconcile firewall (create provider firewall)
            const reconciledFirewall = await this.firewallReconciliationService.reconcile(firewall.id);
            this.logger.log(`Firewall ${firewall.id} reconciled successfully — provider firewall ID: ${reconciledFirewall.providerFirewallId ?? 'NULL (reconciliation may have failed)'}`);
            if (!reconciledFirewall.providerFirewallId) {
                this.logger.error(`Reconciliation returned null providerFirewallId for cluster ${cluster.id} — firewall will NOT be attached to nodes`);
            }
            return reconciledFirewall.providerFirewallId;
        }
        catch (error) {
            this.logger.error(`Failed to create and reconcile firewall for cluster ${cluster.id}: ${error.message}`, error.stack);
            throw error;
        }
    }
    /**
     * Delete firewall for a cluster
     * Called during cluster deletion
     */
    async deleteClusterFirewall(clusterId, provider) {
        this.logger.log(`Deleting firewall for cluster ${clusterId}`);
        try {
            // Get firewall by cluster ID
            const firewall = await this.firewallDesiredStateService.getFirewallByClusterId(clusterId);
            if (!firewall) {
                this.logger.warn(`No firewall found for cluster ${clusterId}`);
                return;
            }
            // Delete provider firewall
            await this.firewallReconciliationService.deleteProviderFirewall(firewall.id);
            // Delete firewall entity
            await this.firewallDesiredStateService.deleteFirewall(firewall.id);
            this.logger.log(`Firewall deleted for cluster ${clusterId}`);
        }
        catch (error) {
            // Log error but don't fail cluster deletion
            this.logger.error(`Failed to delete firewall for cluster ${clusterId}: ${error.message}. Attempting cleanup via labels.`, error.stack);
            // Fallback: cleanup orphaned firewalls by cluster label
            try {
                await this.firewallReconciliationService.cleanupOrphanedFirewalls(clusterId, provider);
                this.logger.log(`Cleaned up orphaned firewalls for cluster ${clusterId} via label selector`);
            }
            catch (cleanupError) {
                this.logger.error(`Failed to cleanup orphaned firewalls for cluster ${clusterId}: ${cleanupError.message}`, cleanupError.stack);
                // Don't throw - allow cluster deletion to continue
            }
        }
    }
};
exports.ClusterFirewallIntegrationService = ClusterFirewallIntegrationService;
exports.ClusterFirewallIntegrationService = ClusterFirewallIntegrationService = ClusterFirewallIntegrationService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [firewall_desired_state_service_1.FirewallDesiredStateService,
        firewall_reconciliation_service_1.FirewallReconciliationService])
], ClusterFirewallIntegrationService);
