"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 EncryptionService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.EncryptionService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const crypto = __importStar(require("node:crypto"));
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const os = __importStar(require("node:os"));
let EncryptionService = EncryptionService_1 = class EncryptionService {
    constructor(configService) {
        this.configService = configService;
        this.logger = new common_1.Logger(EncryptionService_1.name);
        this.algorithm = 'aes-256-gcm';
        this.encryptionKey = this.resolveEncryptionKey();
    }
    /**
     * Resolve encryption key with 3-level fallback:
     * 1. Env var ENCRYPTION_KEY — K8s production (from Kubernetes Secret)
     * 2. File ~/.flui/encryption.key — local development (shared CLI/API)
     * 3. Error if neither is available
     */
    resolveEncryptionKey() {
        // 1. Env var (K8s production or .env)
        const envKey = this.configService.get('ENCRYPTION_KEY');
        if (envKey) {
            const keyBuffer = Buffer.from(envKey, 'hex');
            if (keyBuffer.length !== 32) {
                throw new Error('ENCRYPTION_KEY must be 32 bytes (64 hex characters)');
            }
            this.logger.debug('Using encryption key from environment');
            return keyBuffer;
        }
        // 2. File ~/.flui/encryption.key (shared with CLI) — read or generate
        const fluiDir = path.join(os.homedir(), '.flui');
        const keyFilePath = path.join(fluiDir, 'encryption.key');
        try {
            const fileKey = fs.readFileSync(keyFilePath, 'utf-8').trim();
            const keyBuffer = Buffer.from(fileKey, 'hex');
            if (keyBuffer.length !== 32) {
                throw new Error(`encryption.key file must contain 64 hex characters (32 bytes), got ${fileKey.length} chars`);
            }
            this.logger.debug('Using encryption key from ~/.flui/encryption.key');
            return keyBuffer;
        }
        catch (error) {
            if (error.code !== 'ENOENT') {
                throw error; // Re-throw if not "file not found"
            }
        }
        // 3. Auto-generate key file (first install or after deletion)
        this.logger.log('No encryption key found. Generating new key at ~/.flui/encryption.key');
        const newKey = crypto.randomBytes(32);
        if (!fs.existsSync(fluiDir)) {
            fs.mkdirSync(fluiDir, { recursive: true });
        }
        fs.writeFileSync(keyFilePath, newKey.toString('hex'), {
            encoding: 'utf-8',
            mode: 0o600,
        });
        return newKey;
    }
    /**
     * Encrypt plaintext string using AES-256-GCM
     * @param plaintext String to encrypt
     * @returns Base64 encoded encrypted data (iv + authTag + encrypted)
     */
    encrypt(plaintext) {
        try {
            const iv = crypto.randomBytes(16);
            const cipher = crypto.createCipheriv(this.algorithm, this.encryptionKey, iv);
            const encrypted = Buffer.concat([
                cipher.update(plaintext, 'utf8'),
                cipher.final(),
            ]);
            const authTag = cipher.getAuthTag();
            // Format: iv (16 bytes) + authTag (16 bytes) + encrypted data
            const combined = Buffer.concat([iv, authTag, encrypted]);
            return combined.toString('base64');
        }
        catch (error) {
            this.logger.error('Encryption failed', error.stack);
            throw new Error('Failed to encrypt data');
        }
    }
    /**
     * Decrypt encrypted string
     * @param encryptedData Base64 encoded encrypted data
     * @returns Decrypted plaintext
     */
    decrypt(encryptedData) {
        try {
            const buffer = Buffer.from(encryptedData, 'base64');
            const iv = buffer.subarray(0, 16);
            const authTag = buffer.subarray(16, 32);
            const encrypted = buffer.subarray(32);
            const decipher = crypto.createDecipheriv(this.algorithm, this.encryptionKey, iv);
            decipher.setAuthTag(authTag);
            const decrypted = Buffer.concat([
                decipher.update(encrypted),
                decipher.final(),
            ]);
            return decrypted.toString('utf8');
        }
        catch (error) {
            this.logger.error('Decryption failed', error.stack);
            throw new Error('Failed to decrypt data');
        }
    }
    generateRandomToken(length = 32) {
        return crypto.randomBytes(length).toString('hex');
    }
    /**
     * Generate a secure K3s token for cluster authentication
     *
     * K3s accepts "short token" format: a simple password (minimum 10 characters)
     * We generate 128 characters using a mix of:
     * - Lowercase letters (a-z)
     * - Uppercase letters (A-Z)
     * - Numbers (0-9)
     * - Safe special characters (-_@.+:=)
     *
     * These characters are safe for use in bash scripts, YAML, and K3s configuration.
     *
     * Provides ~778 bits of entropy (practically unbreakable)
     *
     * @returns A 128-character secure token
     */
    generateK3sToken() {
        // Character set: lowercase + uppercase + numbers + safe specials (70 chars total)
        const charset = 'abcdefghijklmnopqrstuvwxyz' + // 26 chars
            'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + // 26 chars
            '0123456789' + // 10 chars
            '-_@.+:='; // 7 safe special chars (no problematic bash/shell chars)
        const tokenLength = 128;
        const randomBytes = crypto.randomBytes(tokenLength);
        let token = '';
        for (let i = 0; i < tokenLength; i++) {
            // Use modulo to map random byte to charset index
            token += charset[randomBytes[i] % charset.length];
        }
        return token;
    }
    hashPassword(password) {
        return crypto.createHash('sha256').update(password).digest('hex');
    }
    compareHash(plaintext, hash) {
        const plaintextHash = this.hashPassword(plaintext);
        return crypto.timingSafeEqual(Buffer.from(plaintextHash), Buffer.from(hash));
    }
};
exports.EncryptionService = EncryptionService;
exports.EncryptionService = EncryptionService = EncryptionService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [config_1.ConfigService])
], EncryptionService);
