'use strict';

/**
 * Contract: key generate
 *
 * Generate API key baru dan menulisnya ke file .env. Default output `.env` di
 * working directory. Mendukung flag `--force` untuk timpa KEY existing.
 *
 * Inline migration v4.0.0: business logic asli dari `keygen.js`
 * di-inline langsung ke handler. Adapter `process.argv` override dihapus
 * karena handler langsung pakai `args.output` dan `args.force`.
 * `process.exit()` di legacy dikonversi menjadi `throw new Error(...)`
 * agar `cli-entry.js` yang handle exit code.
 */

const fs = require('node:fs');
const path = require('node:path');
const { generateApiKey, validateApiKey } = require('../../lib/utils/key-generator');
const { updateEnvKey, hasEnvKey, getEnvValue, backupEnvFile } = require('../../lib/utils/env-manager');
const { validatePathWithinBase } = require('../../lib/utils/path-validator');

module.exports = {
    resource: 'key',
    verb: 'generate',
    description: 'Generate API key baru dan menulisnya ke file .env',
    category: 'management',
    flags: {
        output: {
            type: 'string',
            required: false,
            default: '.env',
            description: 'File output untuk menulis API key'
        },
        force: {
            type: 'boolean',
            required: false,
            default: false,
            description: 'Timpa KEY existing tanpa konfirmasi'
        }
    },
    examples: [
        'npx restforge key generate',
        'npx restforge key generate --output=config/production.env --force'
    ],
    async handler(args) {
        const workingDir = process.cwd();
        const outputFile = validatePathWithinBase(args.output, workingDir);
        const outputRelative = path.relative(workingDir, outputFile);

        console.log('');
        console.log('RestForge API Key Generator');
        console.log('===========================');
        console.log('');

        const fileExists = fs.existsSync(outputFile);
        const keyExists = fileExists && hasEnvKey(outputFile, 'KEY');

        if (keyExists && !args.force) {
            const existingKey = getEnvValue(outputFile, 'KEY');
            const maskedKey = existingKey.substring(0, 12) + '****';

            console.log(`⚠ WARNING: API Key already exists in ${outputRelative}`);
            console.log(`  Current KEY: ${maskedKey}`);
            console.log('');
            console.log('To overwrite, use --force flag:');
            console.log(`  npx restforge key generate --force --output=${args.output}`);
            console.log('');
            console.log('Or revoke existing key first:');
            console.log('  npx restforge key revoke');
            console.log('');
            throw new Error(`API Key already exists in ${outputRelative}. Use --force to overwrite.`);
        }

        let backupPath = null;
        if (fileExists && keyExists) {
            try {
                backupPath = backupEnvFile(outputFile);
                console.log(`✓ Backup created: ${path.relative(workingDir, backupPath)}`);
            } catch (err) {
                console.error(`⚠ Warning: Failed to create backup: ${err.message}`);
            }
        }

        console.log('Generating API key...');
        const apiKey = generateApiKey();

        if (!validateApiKey(apiKey)) {
            throw new Error('Generated key failed validation - this should not happen');
        }

        console.log(`Updating ${outputRelative}...`);

        try {
            updateEnvKey(outputFile, 'KEY', apiKey, true);
        } catch (err) {
            console.error(`Error: Failed to update ${outputRelative}: ${err.message}`);
            throw new Error(`Failed to update ${outputRelative}: ${err.message}`);
        }

        console.log('');
        console.log('✓ API Key generated successfully!');
        console.log(`✓ Updated ${outputRelative}`);
        if (backupPath) {
            console.log(`✓ Backup saved to ${path.relative(workingDir, backupPath)}`);
        }
        console.log('');
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('');
        console.log('Your API Key (save this securely - shown only once):');
        console.log('');
        console.log(`  ${apiKey}`);
        console.log('');
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('');
        console.log('⚠ IMPORTANT SECURITY NOTES:');
        console.log('');
        console.log('  1. Keep this key secure and do not share publicly');
        console.log('  2. Do not commit .env file to git repository');
        console.log('  3. Add .env to .gitignore file');
        console.log('  4. Use different keys for dev/staging/production');
        console.log('  5. Rotate keys periodically for better security');
        console.log('');
        console.log('Next Steps:');
        console.log('');
        console.log('  1. Start server:');
        console.log('     npx restforge serve --project=myapp --config=myapp.env --license=XXX');
        console.log('');
        console.log('  2. Client requests must include header:');
        console.log(`     x-api-key: ${apiKey}`);
        console.log('');
        console.log('  3. List all keys:');
        console.log('     npx restforge key list');
        console.log('');
        console.log('  4. Revoke key if needed:');
        console.log('     npx restforge key revoke');
        console.log('');

        const gitignorePath = path.join(workingDir, '.gitignore');
        if (fs.existsSync(gitignorePath)) {
            const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');
            const hasEnvIgnore = gitignoreContent.includes('.env') ||
                                 gitignoreContent.includes('*.env') ||
                                 gitignoreContent.includes(`${args.output}`);

            if (!hasEnvIgnore) {
                console.log('⚠ WARNING: .gitignore does not contain .env');
                console.log('');
                console.log('Add this line to your .gitignore:');
                console.log('  .env');
                console.log('');
            }
        } else {
            console.log('⚠ WARNING: No .gitignore file found');
            console.log('');
            console.log('Create .gitignore file with:');
            console.log('  .env');
            console.log('');
        }
    }
};
