'use strict';

/**
 * Contract: key list
 *
 * Menampilkan daftar API key yang terdaftar dari file `.env` di working
 * directory (atau directory yang di-specify via `--dir`). Default tampilan
 * dengan masking, gunakan `--show-full` untuk tampilkan key lengkap.
 *
 * Inline migration v4.0.0: business logic asli dari `keylist.js`
 * di-inline langsung ke handler. Adapter `process.argv` override dihapus.
 * `process.exit()` di legacy dikonversi menjadi early return (untuk kondisi
 * normal seperti "no keys found") atau `throw new Error(...)` (untuk error).
 */

const path = require('node:path');
const { findEnvFiles, getEnvValue } = require('../../lib/utils/env-manager');
const { maskApiKey, validateApiKey } = require('../../lib/utils/key-generator');

module.exports = {
    resource: 'key',
    verb: 'list',
    description: 'Menampilkan daftar API key yang terdaftar (default dengan tampilan masked)',
    category: 'management',
    flags: {
        'show-full': {
            type: 'boolean',
            required: false,
            default: false,
            description: 'Tampilkan key full tanpa masking'
        },
        dir: {
            type: 'string',
            required: false,
            default: null,
            description: 'Directory pencarian file .env (default: current working directory)'
        }
    },
    examples: [
        'npx restforge key list',
        'npx restforge key list --show-full --dir=./config'
    ],
    async handler(args) {
        const showFull = args['show-full'] === true;
        const baseDir = path.resolve(args.dir || process.cwd());

        console.log('');
        console.log('RestForge API Key List');
        console.log('======================');
        console.log('');
        console.log(`Scanning directory: ${baseDir}`);
        console.log('');

        const envFiles = findEnvFiles(baseDir);

        if (envFiles.length === 0) {
            console.log('No .env files found in project.');
            console.log('');
            console.log('To generate API key:');
            console.log('  npx restforge key generate');
            console.log('');
            return;
        }

        const keysFound = [];

        for (const filePath of envFiles) {
            const key = getEnvValue(filePath, 'KEY');

            if (key) {
                const relativePath = path.relative(baseDir, filePath);
                const isValid = validateApiKey(key);

                keysFound.push({
                    file: relativePath,
                    fileFull: filePath,
                    key: key,
                    valid: isValid
                });
            }
        }

        if (keysFound.length === 0) {
            console.log('No API keys found in .env files.');
            console.log('');
            console.log('Files scanned:');
            for (let i = 0; i < envFiles.length; i++) {
                const relativePath = path.relative(baseDir, envFiles[i]);
                console.log(`  ${i + 1}. ${relativePath} (no KEY)`);
            }
            console.log('');
            console.log('To generate API key:');
            console.log('  npx restforge key generate');
            console.log('');
            return;
        }

        console.log(`API Keys found: ${keysFound.length}`);
        console.log('');

        for (let i = 0; i < keysFound.length; i++) {
            const item = keysFound[i];
            const num = (i + 1).toString().padStart(2, ' ');

            console.log(`${num}. ${item.file}`);

            if (showFull) {
                console.log(`    Key:    ${item.key}`);
            } else {
                console.log(`    Key:    ${maskApiKey(item.key)}`);
            }

            console.log(`    Valid:  ${item.valid ? '✓ Yes' : '✗ No (invalid format)'}`);
            console.log(`    Length: ${item.key.length} characters`);
            console.log('');
        }

        if (showFull) {
            console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
            console.log('⚠ WARNING: Full keys are displayed above');
            console.log('  - Do not share this output publicly');
            console.log('  - Do not commit screenshot to repository');
            console.log('  - Clear terminal history after viewing');
            console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
            console.log('');
        } else {
            console.log('Tip: Use --show-full to display complete keys (development only)');
            console.log('');
        }

        const invalidKeys = keysFound.filter(item => !item.valid);
        if (invalidKeys.length > 0) {
            console.log('⚠ WARNING: Invalid key format detected');
            console.log('');
            console.log('The following files have invalid KEY format:');
            for (const item of invalidKeys) {
                console.log(`  - ${item.file}`);
            }
            console.log('');
            console.log('Expected format: rk_{64-hex-chars} (total 67 characters)');
            console.log('');
            console.log('To regenerate valid key:');
            console.log(`  npx restforge key generate --force --output=${invalidKeys[0].file}`);
            console.log('');
        }

        console.log('Commands:');
        console.log('  - Generate new key:  npx restforge key generate');
        console.log('  - Revoke key:        npx restforge key revoke');
        console.log('  - Server usage:      npx restforge serve --project=myapp --config=myapp.env');
        console.log('');
    }
};
