'use strict';

/**
 * Contract: init (verb global)
 *
 * Generate starter config file di working directory. Membuat
 * `config/db-connection.env` sebagai template starting point.
 *
 * Inline migration v4.0.0: business logic asli dari `init.js` di-inline
 * langsung ke handler. Adapter `process.argv` override dihapus. `process.exit()`
 * di legacy dikonversi menjadi `throw new Error(...)` agar `cli-entry.js` yang
 * handle exit code.
 *
 * Catatan: contract ini global verb (snapshot key = `init`, bukan
 * `<resource>/init`). Struktur file di `generators/cli/init.js` (root cli/
 * directory, bukan subdirectory resource).
 */

const path = require('node:path');
const fs = require('node:fs');
const { DB_CONNECTION_ENV_TEMPLATE: TEMPLATE_ENV } = require('../lib/templates/db-connection-env');

module.exports = {
    verb: 'init',
    description: 'Generate starter config file (config/db-connection.env) di working directory',
    category: 'utility',
    flags: {
        force: {
            type: 'boolean',
            required: false,
            default: false,
            description: 'Timpa file existing tanpa konfirmasi'
        }
    },
    examples: [
        'npx restforge init',
        'npx restforge init --force'
    ],
    async handler(args) {
        const workingDir = process.cwd();

        console.log('');
        console.log('RESTForge - Init');
        console.log('====================');
        console.log('');

        const files = [
            {
                relativePath: path.join('config', 'db-connection.env'),
                content: TEMPLATE_ENV
            }
        ];

        for (const file of files) {
            file.absolutePath = path.resolve(workingDir, file.relativePath);
        }

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

        if (existingFiles.length > 0 && !args.force) {
            console.log('WARNING: The following files already exist:');
            console.log('');
            for (const file of existingFiles) {
                console.log(`  ${file.relativePath}`);
            }
            console.log('');
            console.log('Use --force to overwrite:');
            console.log('  npx restforge init --force');
            console.log('');
            throw new Error(`${existingFiles.length} file(s) already exist. Use --force to overwrite.`);
        }

        const dirs = [
            path.resolve(workingDir, 'config')
        ];

        for (const dir of dirs) {
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true });
            }
        }

        for (const file of files) {
            fs.writeFileSync(file.absolutePath, file.content, 'utf8');
            console.log(`  Created: ${file.relativePath}`);
        }

        console.log('');
        console.log('Done! Sample files generated successfully.');
        console.log('');
        console.log('Next Steps:');
        console.log('');
        console.log('  1. Edit config/db-connection.env');
        console.log('     Update database credentials (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)');
        console.log('');
    }
};
