"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 CliClusterRepository_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CliClusterRepository = void 0;
const common_1 = require("@nestjs/common");
const cluster_entity_1 = require("../../../../src/modules/infrastructure/clusters/entities/cluster.entity");
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 Cluster Repository for CLI
 *
 * Persists cluster data in ~/.flui/clusters.json
 * Provides TypeORM-like interface without requiring database
 */
let CliClusterRepository = CliClusterRepository_1 = class CliClusterRepository {
    constructor() {
        this.logger = new common_1.Logger(CliClusterRepository_1.name);
        this.dataDir = profile_manager_1.ProfileManager.getProfileDir();
        this.dataFile = path.join(this.dataDir, 'clusters.json');
        this.ensureDataDir();
    }
    /**
     * Ensure profile directory exists
     */
    ensureDataDir() {
        if (!fs.existsSync(this.dataDir)) {
            fs.mkdirSync(this.dataDir, { recursive: true, mode: 0o700 });
        }
    }
    /**
     * Load all clusters from file
     */
    loadClusters() {
        if (!fs.existsSync(this.dataFile)) {
            return [];
        }
        try {
            const data = fs.readFileSync(this.dataFile, 'utf-8');
            const clusters = JSON.parse(data);
            // Convert plain objects to ClusterEntity instances
            return clusters.map((cluster) => {
                const entity = new cluster_entity_1.ClusterEntity();
                Object.assign(entity, cluster);
                // Convert nodes to ClusterNodeEntity instances
                if (cluster.nodes) {
                    entity.nodes = cluster.nodes.map((node) => {
                        const nodeEntity = new cluster_node_entity_1.ClusterNodeEntity();
                        Object.assign(nodeEntity, node);
                        return nodeEntity;
                    });
                }
                return entity;
            });
        }
        catch (error) {
            this.logger.error(`Failed to load clusters from ${this.dataFile}:`, error);
            return [];
        }
    }
    /**
     * Save all clusters to file
     */
    saveClusters(clusters) {
        try {
            const data = JSON.stringify(clusters, null, 2);
            fs.writeFileSync(this.dataFile, data, { encoding: 'utf-8', mode: 0o600 });
            this.logger.debug(`Saved ${clusters.length} clusters to ${this.dataFile}`);
        }
        catch (error) {
            this.logger.error(`Failed to save clusters to ${this.dataFile}:`, error);
            throw error;
        }
    }
    /**
     * Create a new cluster entity (doesn't save to file yet)
     * This mimics TypeORM's Repository.create() method
     */
    create(data) {
        const entity = new cluster_entity_1.ClusterEntity();
        Object.assign(entity, data);
        return entity;
    }
    /**
     * Find one cluster by criteria
     */
    async findOne(options) {
        const clusters = this.loadClusters();
        if (!options.where) {
            return clusters.length > 0 ? clusters[0] : null;
        }
        const cluster = clusters.find((c) => {
            // Match all where conditions
            return Object.entries(options.where).every(([key, value]) => {
                // Handle nested metadata matching
                if (key === 'metadata' && typeof value === 'object') {
                    return Object.entries(value).every(([metaKey, metaValue]) => {
                        return c.metadata?.[metaKey] === metaValue;
                    });
                }
                return c[key] === value;
            });
        });
        return cluster || null;
    }
    /**
     * Find all clusters matching criteria
     */
    async find(options) {
        const clusters = this.loadClusters();
        if (!options?.where) {
            return clusters;
        }
        return clusters.filter((c) => {
            return Object.entries(options.where).every(([key, value]) => {
                if (key === 'metadata' && typeof value === 'object') {
                    return Object.entries(value).every(([metaKey, metaValue]) => {
                        return c.metadata?.[metaKey] === metaValue;
                    });
                }
                return c[key] === value;
            });
        });
    }
    /**
     * Save cluster (create or update)
     */
    async save(cluster) {
        const clusters = this.loadClusters();
        // Generate ID if new cluster
        if (!cluster.id) {
            cluster.id = this.generateId();
            cluster.createdAt = new Date();
        }
        cluster.updatedAt = new Date();
        // Find and replace existing, or add new
        const index = clusters.findIndex((c) => c.id === cluster.id);
        if (index >= 0) {
            clusters[index] = cluster;
            this.logger.debug(`Updated cluster ${cluster.id}`);
        }
        else {
            clusters.push(cluster);
            this.logger.debug(`Created cluster ${cluster.id}`);
        }
        this.saveClusters(clusters);
        return cluster;
    }
    /**
     * Delete cluster
     */
    async remove(cluster) {
        const clusters = this.loadClusters();
        const filtered = clusters.filter((c) => c.id !== cluster.id);
        if (filtered.length < clusters.length) {
            this.saveClusters(filtered);
            this.logger.debug(`Deleted cluster ${cluster.id}`);
        }
        return cluster;
    }
    /**
     * Generate unique ID (UUID v4, compatible with PostgreSQL)
     */
    generateId() {
        return (0, uuid_1.v4)();
    }
};
exports.CliClusterRepository = CliClusterRepository;
exports.CliClusterRepository = CliClusterRepository = CliClusterRepository_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [])
], CliClusterRepository);
