'use strict';

/**
 * Contract: config set-default
 *
 * Set file config sebagai default untuk working directory saat ini. Disimpan
 * di {cwd}/.restforge/defaults.json. Setelah di-set, command yang menerima
 * --config dapat dijalankan tanpa parameter eksplisit.
 *
 * Inline migration v4.0.0: business logic asli dari config-set-default.js
 * di-inline langsung di handler. Adapter process.argv override dihapus karena
 * handler langsung pakai args.config. process.exit() di legacy dikonversi
 * menjadi throw new Error(...) agar cli-entry.js yang handle exit code.
 */

const fs = require('node:fs');
const {
    setDefaultConfig,
    resolveConfigFilePath
} = require('../../lib/utils/config-resolver');

module.exports = {
    resource: 'config',
    verb: 'set-default',
    description: 'Set file config sebagai default untuk working directory saat ini (disimpan di .restforge/defaults.json)',
    category: 'management',
    flags: {
        config: {
            type: 'string',
            required: true,
            description: 'File config yang dijadikan default (lookup: cwd -> config/ folder -> +.env extension)'
        }
    },
    examples: [
        'npx restforge config set-default --config=config/db-connection.env',
        'npx restforge config set-default --config=db-postgres.env'
    ],
    async handler(args) {
        const configFile = args.config;
        const cwd = process.cwd();
        const resolvedPath = resolveConfigFilePath(configFile, cwd);

        if (!fs.existsSync(resolvedPath)) {
            console.error('Error: Config file not found');
            console.error(`  Searched as: ${configFile}`);
            console.error(`  Resolved to: ${resolvedPath}`);
            console.error('');
            console.error('Lookup order: cwd -> config/ folder -> +.env extension');
            throw new Error('Config file not found');
        }

        const { filePath } = setDefaultConfig(configFile, cwd);

        console.log('');
        console.log('Default config set successfully');
        console.log('');
        console.log(`  Config name : ${configFile}`);
        console.log(`  Resolved to : ${resolvedPath}`);
        console.log(`  Stored at   : ${filePath}`);
        console.log('');
        console.log('Commands accepting --config can now run without specifying it.');
        console.log("Verify with: npx restforge config get-default");
        console.log('');
    }
};
