'use strict';

/**
 * Contract: kafka consumer-create
 *
 * Generate Kafka consumer code dari payload JSON.
 *
 * Inline migration v4.0.0: business logic dipindah dari
 * consumer-create.js ke handler ini secara langsung.
 *
 * Note hotfix Fase 04: flag `--name` di contract (public, konsisten dengan
 * command-standard.md) sebelumnya di-translate ke `--consumer` di legacy argv.
 * Setelah inline, translation tidak lagi diperlukan karena handler langsung
 * pakai `args.name`.
 */

const path = require('path');
const fs = require('fs');
const readline = require('readline');
const ConsumerGenerator = require('../../lib/generators/consumer-generator');

function prompt(question) {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    return new Promise((resolve) => {
        rl.question(question, (answer) => {
            rl.close();
            resolve(answer.trim().toLowerCase());
        });
    });
}

function validateConsumerName(consumerName) {
    if (!consumerName || typeof consumerName !== 'string') {
        throw new Error('Consumer name cannot be empty');
    }

    const trimmed = consumerName.trim();

    if (trimmed.length === 0) {
        throw new Error('Consumer name cannot be empty');
    }

    if (trimmed.length > 50) {
        throw new Error('Consumer name cannot exceed 50 characters');
    }

    const validPattern = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
    if (!validPattern.test(trimmed)) {
        throw new Error('Consumer name can only contain letters, numbers, dash (-), and underscore (_), and must start with a letter or number');
    }

    return trimmed.toLowerCase();
}

function validateProjectName(projectName) {
    if (!projectName || typeof projectName !== 'string') {
        throw new Error('Project name cannot be empty');
    }

    const trimmed = projectName.trim();

    if (trimmed.length === 0) {
        throw new Error('Project name cannot be empty');
    }

    if (trimmed.length > 50) {
        throw new Error('Project name cannot exceed 50 characters');
    }

    const validPattern = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
    if (!validPattern.test(trimmed)) {
        throw new Error('Project name can only contain letters, numbers, dash (-), and underscore (_), and must start with a letter or number');
    }

    return trimmed.toLowerCase();
}

function resolvePayloadPath(payloadName) {
    if (path.isAbsolute(payloadName)) {
        return payloadName;
    }

    if (payloadName.includes('/') || payloadName.includes('\\')) {
        return path.resolve(process.cwd(), payloadName);
    }

    let filename = payloadName;
    if (!filename.endsWith('.json')) {
        filename += '.json';
    }

    return path.resolve(process.cwd(), 'payload', filename);
}

module.exports = {
    resource: 'kafka',
    verb: 'consumer-create',
    description: 'Generate Kafka consumer code dari payload JSON',
    category: 'generation',
    flags: {
        project: {
            type: 'string',
            required: true,
            description: 'Nama project target'
        },
        name: {
            type: 'string',
            required: true,
            description: 'Nama consumer yang akan dibuat'
        },
        payload: {
            type: 'string',
            required: true,
            description: 'Path atau nama file payload JSON consumer'
        },
        force: {
            type: 'boolean',
            required: false,
            default: false,
            description: 'Timpa file existing'
        }
    },
    examples: [
        'npx restforge kafka consumer-create --project=my-app --name=order-events --payload=order-events.json',
        'npx restforge kafka consumer-create --project=my-app --name=order-events --payload=order-events.json --force'
    ],
    async handler(args) {
        console.log('');
        console.log('RESTForge Consumer Generator');
        console.log('============================');
        console.log('');

        let projectName, consumerName;
        try {
            projectName = validateProjectName(args.project);
            consumerName = validateConsumerName(args.name);
        } catch (error) {
            console.error(`Error: ${error.message}`);
            throw error;
        }

        const payloadPath = resolvePayloadPath(args.payload);

        if (!fs.existsSync(payloadPath)) {
            console.error(`Error: Payload file not found: ${payloadPath}`);
            console.log('');
            console.log('Make sure the payload file exists in the payload/ folder');
            console.log('or provide a full path to the file.');
            throw new Error(`Payload file not found: ${payloadPath}`);
        }

        console.log('Arguments to be processed:');
        console.log(`  Project: ${projectName}`);
        console.log(`  Consumer: ${consumerName}`);
        console.log(`  Payload: ${payloadPath}`);
        console.log(`  Force overwrite: ${args.force}`);
        console.log('');

        let payload;
        try {
            const payloadContent = fs.readFileSync(payloadPath, 'utf8');
            payload = JSON.parse(payloadContent);
        } catch (error) {
            if (error instanceof SyntaxError) {
                console.error(`Error: Invalid JSON in payload file: ${error.message}`);
                throw new Error(`Invalid JSON in payload file: ${error.message}`);
            }
            console.error(`Error: ${error.message}`);
            throw error;
        }

        payload.consumerName = consumerName;

        console.log(`Consumer Name: ${payload.consumerName}`);
        console.log(`Description: ${payload.description || 'N/A'}`);
        console.log(`Target Type: ${payload.target?.type || 'N/A'}`);
        console.log(`Topic: ${payload.kafka?.topic || 'N/A'}`);
        console.log('');

        const consumerDir = path.resolve(process.cwd(), 'src', 'consumers', projectName, consumerName);
        const metadataDir = path.resolve(process.cwd(), 'metadata', 'consumers');
        const demoDir = path.resolve(process.cwd(), 'demo');

        const filesToCheck = [
            path.join(consumerDir, 'consumer.js'),
            path.join(consumerDir, 'handler.js'),
            path.join(consumerDir, 'index.js'),
            path.join(metadataDir, `${consumerName}.json`),
            path.join(demoDir, `consumer-${consumerName}-test.json`)
        ];

        const existingFiles = filesToCheck.filter(f => fs.existsSync(f));

        let forceOverwrite = args.force;

        if (existingFiles.length > 0 && !forceOverwrite) {
            console.log('');
            console.log('WARNING: The following files already exist:');
            existingFiles.forEach(f => {
                const relativePath = path.relative(process.cwd(), f);
                console.log(`  - ${relativePath}`);
            });
            console.log('');
            console.log('Options:');
            console.log('  [1] Overwrite all existing files');
            console.log('  [2] Skip existing files (only create new)');
            console.log('  [3] Cancel generation');
            console.log('');

            const answer = await prompt('Your choice (1/2/3): ');

            if (answer === '1') {
                forceOverwrite = true;
                console.log('');
                console.log('Proceeding with overwrite...');
            } else if (answer === '2') {
                forceOverwrite = false;
                console.log('');
                console.log('Proceeding, will skip existing files...');
            } else {
                console.log('');
                console.log('Generation cancelled.');
                return;
            }
            console.log('');
        }

        const result = await ConsumerGenerator.generate(
            consumerName,
            payload,
            {
                force: forceOverwrite,
                projectName: projectName,
                outputDir: consumerDir
            }
        );

        if (result.success) {
            console.log('');
            console.log('Generation completed successfully!');
            console.log('');
            console.log('Generated files:');
            if (result.files && result.files.length > 0) {
                result.files.forEach(file => console.log(`  - ${file}`));
            }
            console.log('');
            console.log('Next steps:');
            console.log(`  1. cd src/consumers/${projectName}/${consumerName}`);
            console.log(`  2. Review generated files`);
            console.log(`  3. Run consumer: npx restforge-consumer --project=${projectName} --consumer=${consumerName}`);
            console.log('');
            return;
        }

        console.error('');
        console.error('Generation failed with errors:');
        result.errors.forEach(err => console.error(`  - ${err}`));
        throw new Error(`Consumer generation failed: ${result.errors.join('; ')}`);
    }
};
