"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 __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var CliNodeRepository_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CliNodeRepository = void 0;
const common_1 = require("@nestjs/common");
const cluster_node_entity_1 = require("../../../../src/modules/infrastructure/clusters/entities/cluster-node.entity");
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const uuid_1 = require("uuid");
const profile_manager_1 = require("../profile-manager");
/**
 * File-based ClusterNode Repository for CLI
 *
 * Persists cluster node data in the active profile directory.
 * Provides TypeORM-like interface without requiring database.
 */
let CliNodeRepository = CliNodeRepository_1 = class CliNodeRepository {
    constructor() {
        this.logger = new common_1.Logger(CliNodeRepository_1.name);
        this.dataDir = profile_manager_1.ProfileManager.getProfileDir();
        this.dataFile = path.join(this.dataDir, 'nodes.json');
        this.ensureDataDir();
    }
    ensureDataDir() {
        if (!fs.existsSync(this.dataDir)) {
            fs.mkdirSync(this.dataDir, { recursive: true, mode: 0o700 });
        }
    }
    loadNodes() {
        if (!fs.existsSync(this.dataFile)) {
            return [];
        }
        try {
            const data = fs.readFileSync(this.dataFile, 'utf-8');
            const nodes = JSON.parse(data);
            return nodes.map((node) => {
                const entity = new cluster_node_entity_1.ClusterNodeEntity();
                Object.assign(entity, node);
                if (node.createdAt)
                    entity.createdAt = new Date(node.createdAt);
                if (node.updatedAt)
                    entity.updatedAt = new Date(node.updatedAt);
                return entity;
            });
        }
        catch (error) {
            this.logger.error(`Failed to load nodes from ${this.dataFile}:`, error);
            return [];
        }
    }
    saveNodes(nodes) {
        try {
            const data = JSON.stringify(nodes, null, 2);
            fs.writeFileSync(this.dataFile, data, { encoding: 'utf-8', mode: 0o600 });
            this.logger.debug(`Saved ${nodes.length} nodes to ${this.dataFile}`);
        }
        catch (error) {
            this.logger.error(`Failed to save nodes to ${this.dataFile}:`, error);
            throw error;
        }
    }
    create(data) {
        const entity = new cluster_node_entity_1.ClusterNodeEntity();
        Object.assign(entity, data);
        return entity;
    }
    async findOne(options) {
        const matches = await this.find(options);
        return matches[0] ?? null;
    }
    async find(options) {
        let nodes = this.loadNodes();
        if (options?.where) {
            nodes = nodes.filter((node) => {
                return Object.entries(options.where).every(([key, value]) => {
                    return node[key] === value;
                });
            });
        }
        return nodes;
    }
    async save(node) {
        const nodes = this.loadNodes();
        const nodesToSave = Array.isArray(node) ? node : [node];
        const isArray = Array.isArray(node);
        for (const n of nodesToSave) {
            if (!n.id) {
                n.id = this.generateId();
                n.createdAt = new Date();
            }
            n.updatedAt = new Date();
            const index = nodes.findIndex((existing) => existing.id === n.id);
            if (index >= 0) {
                nodes[index] = n;
                this.logger.debug(`Updated node ${n.id}`);
            }
            else {
                nodes.push(n);
                this.logger.debug(`Created node ${n.id}`);
            }
        }
        this.saveNodes(nodes);
        return isArray ? nodesToSave : nodesToSave[0];
    }
    async remove(node) {
        const nodes = this.loadNodes();
        const filtered = nodes.filter((n) => n.id !== node.id);
        if (filtered.length < nodes.length) {
            this.saveNodes(filtered);
            this.logger.debug(`Deleted node ${node.id}`);
        }
        return node;
    }
    generateId() {
        return (0, uuid_1.v4)();
    }
};
exports.CliNodeRepository = CliNodeRepository;
exports.CliNodeRepository = CliNodeRepository = CliNodeRepository_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [])
], CliNodeRepository);
