const crypto = require('crypto');

/**
 * API Key Generator Utility
 *
 * Generates secure random API keys untuk RestForge authentication
 * Format: rk_{64-hex-chars}
 *
 * @module lib/utils/key-generator
 */

/**
 * Generate random API key dengan format restforge
 *
 * Format: rk_{random-64-hex-chars}
 * Length: 67 characters total (3 prefix + 64 hex)
 * Security: 32 bytes = 256 bits entropy
 *
 * @returns {string} Generated API key
 *
 * @example
 * const key = generateApiKey();
 * // Returns: rk_1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z7a8b9c0d1e2f3g4
 */
function generateApiKey() {
    const prefix = 'rk_';
    const randomBytes = crypto.randomBytes(32); // 32 bytes = 256 bits
    const randomHex = randomBytes.toString('hex'); // 64 hex chars

    return prefix + randomHex;
}

/**
 * Validate API key format
 *
 * Checks:
 * - Starts with 'rk_' prefix
 * - Total length is 67 characters (3 + 64)
 * - Random part contains only hex characters (0-9, a-f)
 *
 * @param {string} key - API key to validate
 * @returns {boolean} True if valid format
 *
 * @example
 * validateApiKey('rk_1a2b3c4d...'); // true
 * validateApiKey('invalid_key');    // false
 * validateApiKey('rk_short');       // false
 */
function validateApiKey(key) {
    if (typeof key !== 'string') {
        return false;
    }

    // Check prefix
    if (!key.startsWith('rk_')) {
        return false;
    }

    // Check total length: 3 (prefix) + 64 (hex) = 67
    if (key.length !== 67) {
        return false;
    }

    // Extract random part (after 'rk_')
    const randomPart = key.substring(3);

    // Check if random part is valid hex (64 chars, only 0-9 a-f)
    const hexRegex = /^[0-9a-f]{64}$/i;
    return hexRegex.test(randomPart);
}

/**
 * Hash API key untuk secure storage
 *
 * Uses SHA-256 hashing untuk store key di database
 * (Future enhancement - saat implement database-backed key management)
 *
 * @param {string} key - Plain API key
 * @returns {string} SHA-256 hash (64 hex chars)
 *
 * @example
 * const hash = hashApiKey('rk_1a2b3c4d...');
 * // Returns: '5d41402abc4b2a76b9719d911017c592...'
 */
function hashApiKey(key) {
    return crypto
        .createHash('sha256')
        .update(key)
        .digest('hex');
}

/**
 * Mask API key untuk safe display
 *
 * Shows first 12 characters, masks the rest
 * Format: rk_1a2b3c4d**** (52 chars hidden)
 *
 * @param {string} key - API key to mask
 * @param {number} [visibleChars=12] - Number of chars to show
 * @returns {string} Masked key
 *
 * @example
 * maskApiKey('rk_1a2b3c4d5e6f7g8h...');
 * // Returns: 'rk_1a2b3c4d**** (55 chars hidden)'
 */
function maskApiKey(key, visibleChars = 12) {
    if (typeof key !== 'string' || key.length <= visibleChars) {
        return key;
    }

    const visible = key.substring(0, visibleChars);
    const hiddenCount = key.length - visibleChars;

    return `${visible}**** (${hiddenCount} chars hidden)`;
}

/**
 * Generate multiple API keys
 *
 * Useful untuk batch generation atau testing
 *
 * @param {number} count - Number of keys to generate
 * @returns {string[]} Array of generated keys
 *
 * @example
 * const keys = generateMultipleKeys(5);
 * // Returns: ['rk_...', 'rk_...', 'rk_...', 'rk_...', 'rk_...']
 */
function generateMultipleKeys(count) {
    const keys = [];
    for (let i = 0; i < count; i++) {
        keys.push(generateApiKey());
    }
    return keys;
}

module.exports = {
    generateApiKey,
    validateApiKey,
    hashApiKey,
    maskApiKey,
    generateMultipleKeys
};
