"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 CliOperationRepository_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CliOperationRepository = void 0;
const common_1 = require("@nestjs/common");
const infrastructure_operations_entity_1 = require("../../../../src/modules/infrastructure/servers/entities/infrastructure-operations.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 Operation Repository for CLI
 *
 * Persists infrastructure operation data in ~/.flui/operations.json
 * Provides TypeORM-like interface without requiring database
 */
let CliOperationRepository = CliOperationRepository_1 = class CliOperationRepository {
    constructor() {
        this.logger = new common_1.Logger(CliOperationRepository_1.name);
        this.dataDir = profile_manager_1.ProfileManager.getProfileDir();
        this.dataFile = path.join(this.dataDir, 'operations.json');
        this.ensureDataDir();
    }
    ensureDataDir() {
        if (!fs.existsSync(this.dataDir)) {
            fs.mkdirSync(this.dataDir, { recursive: true, mode: 0o700 });
        }
    }
    /**
     * Load all operations from file
     */
    loadOperations() {
        if (!fs.existsSync(this.dataFile)) {
            return [];
        }
        try {
            const data = fs.readFileSync(this.dataFile, 'utf-8');
            const operations = JSON.parse(data);
            // Convert plain objects to InfrastructureOperationEntity instances
            return operations.map((op) => {
                const entity = new infrastructure_operations_entity_1.InfrastructureOperationEntity();
                Object.assign(entity, op);
                // Parse dates
                if (op.createdAt)
                    entity.createdAt = new Date(op.createdAt);
                if (op.updatedAt)
                    entity.updatedAt = new Date(op.updatedAt);
                return entity;
            });
        }
        catch (error) {
            this.logger.error(`Failed to load operations from ${this.dataFile}:`, error);
            return [];
        }
    }
    /**
     * Save all operations to file
     */
    saveOperations(operations) {
        try {
            const data = JSON.stringify(operations, null, 2);
            fs.writeFileSync(this.dataFile, data, { encoding: 'utf-8', mode: 0o600 });
            this.logger.debug(`Saved ${operations.length} operations to ${this.dataFile}`);
        }
        catch (error) {
            this.logger.error(`Failed to save operations to ${this.dataFile}:`, error);
            throw error;
        }
    }
    /**
     * Create a new operation entity (doesn't save to file yet)
     * This mimics TypeORM's Repository.create() method
     */
    create(data) {
        const entity = new infrastructure_operations_entity_1.InfrastructureOperationEntity();
        Object.assign(entity, data);
        return entity;
    }
    /**
     * Find one operation by criteria
     */
    async findOne(options) {
        let operations = this.loadOperations();
        // Filter by where clause
        if (options.where) {
            operations = operations.filter((op) => {
                return Object.entries(options.where).every(([key, value]) => {
                    return op[key] === value;
                });
            });
        }
        // Apply ordering
        if (options.order) {
            const [[orderKey, orderDir]] = Object.entries(options.order);
            operations.sort((a, b) => {
                const aVal = a[orderKey];
                const bVal = b[orderKey];
                let comparison = 0;
                if (aVal > bVal)
                    comparison = 1;
                else if (aVal < bVal)
                    comparison = -1;
                return orderDir === 'ASC' ? comparison : -comparison;
            });
        }
        return operations.length > 0 ? operations[0] : null;
    }
    /**
     * Find all operations matching criteria
     */
    async find(options) {
        let operations = this.loadOperations();
        // Filter by where clause
        if (options?.where) {
            operations = operations.filter((op) => {
                return Object.entries(options.where).every(([key, value]) => {
                    return op[key] === value;
                });
            });
        }
        // Apply ordering
        if (options?.order) {
            const [[orderKey, orderDir]] = Object.entries(options.order);
            operations.sort((a, b) => {
                const aVal = a[orderKey];
                const bVal = b[orderKey];
                let comparison = 0;
                if (aVal > bVal)
                    comparison = 1;
                else if (aVal < bVal)
                    comparison = -1;
                return orderDir === 'ASC' ? comparison : -comparison;
            });
        }
        return operations;
    }
    /**
     * Save operation (create or update)
     */
    async save(operation) {
        const operations = this.loadOperations();
        // Generate ID if new operation
        if (!operation.id) {
            operation.id = this.generateId();
            operation.createdAt = new Date();
        }
        operation.updatedAt = new Date();
        // Find and replace existing, or add new
        const index = operations.findIndex((op) => op.id === operation.id);
        if (index >= 0) {
            operations[index] = operation;
            this.logger.debug(`Updated operation ${operation.id}`);
        }
        else {
            operations.push(operation);
            this.logger.debug(`Created operation ${operation.id}`);
        }
        this.saveOperations(operations);
        return operation;
    }
    /**
     * Delete operation
     */
    async remove(operation) {
        const operations = this.loadOperations();
        const filtered = operations.filter((op) => op.id !== operation.id);
        if (filtered.length < operations.length) {
            this.saveOperations(filtered);
            this.logger.debug(`Deleted operation ${operation.id}`);
        }
        return operation;
    }
    /**
     * Generate unique ID (UUID v4, compatible with PostgreSQL)
     */
    generateId() {
        return (0, uuid_1.v4)();
    }
};
exports.CliOperationRepository = CliOperationRepository;
exports.CliOperationRepository = CliOperationRepository = CliOperationRepository_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [])
], CliOperationRepository);
