"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
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 __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var CliFirewallRepository_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CliFirewallRepository = void 0;
const common_1 = require("@nestjs/common");
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("node:path"));
const profile_manager_1 = require("../profile-manager");
let CliFirewallRepository = CliFirewallRepository_1 = class CliFirewallRepository {
    constructor() {
        this.dataFile = path.join(profile_manager_1.ProfileManager.getProfileDir(), 'firewalls.json');
        this.logger = new common_1.Logger(CliFirewallRepository_1.name);
    }
    async save(firewall) {
        const data = await this.load();
        const index = data.firewalls.findIndex((f) => f.id === firewall.id);
        const now = new Date().toISOString();
        if (index >= 0) {
            data.firewalls[index] = {
                ...firewall,
                updatedAt: now,
            };
            this.logger.log(`Updated firewall ${firewall.name} in storage`);
        }
        else {
            data.firewalls.push({
                ...firewall,
                createdAt: now,
                updatedAt: now,
            });
            this.logger.log(`Added firewall ${firewall.name} to storage`);
        }
        data.metadata.lastSync = now;
        await this.persist(data);
    }
    async findByClusterId(clusterId) {
        const data = await this.load();
        const firewall = data.firewalls.find((f) => f.clusterId === clusterId);
        if (firewall) {
            this.logger.debug(`Found firewall for cluster ${clusterId}: ${firewall.name}`);
        }
        return firewall || null;
    }
    async findById(id) {
        const data = await this.load();
        return data.firewalls.find((f) => f.id === id) || null;
    }
    async findByName(name) {
        const data = await this.load();
        return data.firewalls.find((f) => f.name === name) || null;
    }
    async findAll() {
        const data = await this.load();
        return data.firewalls;
    }
    async findByProvider(provider) {
        const data = await this.load();
        return data.firewalls.filter((f) => f.provider === provider);
    }
    async delete(id) {
        const data = await this.load();
        const initialLength = data.firewalls.length;
        data.firewalls = data.firewalls.filter((f) => f.id !== id);
        if (data.firewalls.length < initialLength) {
            data.metadata.lastSync = new Date().toISOString();
            await this.persist(data);
            this.logger.log(`Deleted firewall ${id} from storage`);
        }
        else {
            this.logger.warn(`Firewall ${id} not found in storage`);
        }
    }
    async load() {
        try {
            if (await fs.pathExists(this.dataFile)) {
                const content = await fs.readJSON(this.dataFile);
                return content;
            }
        }
        catch (error) {
            this.logger.warn(`Failed to load firewalls storage: ${error.message}`);
        }
        // Return default structure
        return {
            firewalls: [],
            metadata: {
                version: '1.0.0',
                lastSync: new Date().toISOString(),
            },
        };
    }
    async persist(data) {
        const dir = path.dirname(this.dataFile);
        // Ensure directory exists with secure permissions
        await fs.ensureDir(dir);
        await fs.chmod(dir, 0o700);
        // Write file with pretty formatting
        await fs.writeJSON(this.dataFile, data, {
            spaces: 2,
            mode: 0o600, // Read/write for owner only
        });
        this.logger.debug(`Persisted ${data.firewalls.length} firewalls to storage`);
    }
};
exports.CliFirewallRepository = CliFirewallRepository;
exports.CliFirewallRepository = CliFirewallRepository = CliFirewallRepository_1 = __decorate([
    (0, common_1.Injectable)()
], CliFirewallRepository);
