'use strict';

/**
 * Contract: config list
 *
 * Menampilkan daftar file .env yang tersedia di working directory dan folder
 * config/. Berguna untuk melihat config apa saja yang bisa dipakai sebagai
 * default.
 *
 * Inline migration v4.0.0: business logic asli dari config-list.js
 * di-inline langsung di handler. Adapter process.argv override dihapus karena
 * handler langsung pakai args.pretty. process.exit() dikonversi ke return.
 */

const fs = require('node:fs');
const path = require('node:path');
const { getDefaultConfig } = require('../../lib/utils/config-resolver');

function listEnvFilesInDir(dirPath) {
    if (!fs.existsSync(dirPath)) {
        return [];
    }

    const entries = fs.readdirSync(dirPath, { withFileTypes: true });
    const result = [];

    for (const entry of entries) {
        if (entry.isFile() && entry.name.endsWith('.env')) {
            const fullPath = path.join(dirPath, entry.name);
            let size = 0;
            try {
                size = fs.statSync(fullPath).size;
            } catch (_e) {
                size = 0;
            }
            result.push({
                name: entry.name,
                path: fullPath,
                size
            });
        }
    }

    return result;
}

function isMatchingDefault(fileName, location, defaultName) {
    if (!defaultName) return false;

    if (defaultName === fileName) return true;

    if (location === 'config' && defaultName === fileName) return true;

    const defaultBase = path.basename(defaultName);
    if (defaultBase === fileName) return true;

    return false;
}

module.exports = {
    resource: 'config',
    verb: 'list',
    description: 'Menampilkan daftar file .env yang tersedia di working directory dan folder config/',
    category: 'introspection',
    flags: {
        pretty: {
            type: 'boolean',
            required: false,
            default: true,
            description: 'Pretty-print output JSON'
        }
    },
    examples: [
        'npx restforge config list',
        'npx restforge config list --pretty=false'
    ],
    async handler(args) {
        const pretty = args.pretty !== false;
        const cwd = process.cwd();
        const def = getDefaultConfig(cwd);
        const defaultName = def ? def.config : null;

        const cwdFiles = listEnvFilesInDir(cwd).map(f => ({
            ...f,
            location: 'cwd',
            isDefault: isMatchingDefault(f.name, 'cwd', defaultName)
        }));

        const configDir = path.join(cwd, 'config');
        const configFiles = listEnvFilesInDir(configDir).map(f => ({
            ...f,
            location: 'config',
            isDefault: isMatchingDefault(f.name, 'config', defaultName)
        }));

        const all = [...cwdFiles, ...configFiles];

        if (!pretty) {
            console.log(JSON.stringify({
                cwd,
                defaultConfig: defaultName,
                total: all.length,
                files: all.map(f => ({
                    name: f.name,
                    location: f.location,
                    path: f.path,
                    size: f.size,
                    isDefault: f.isDefault
                }))
            }));
            return;
        }

        console.log('');
        console.log(`Working directory: ${cwd}`);
        if (defaultName) {
            console.log(`Default config   : ${defaultName}`);
        } else {
            console.log('Default config   : (not set)');
        }
        console.log('');

        if (all.length === 0) {
            console.log('No .env files found in working directory or config/ folder.');
            console.log('');
            console.log('Generate a starter config with: npx restforge init');
            console.log('');
            return;
        }

        const colName = 32;
        const colLocation = 12;
        const colSize = 10;
        const colDefault = 10;

        console.log(
            'File'.padEnd(colName) +
            'Location'.padEnd(colLocation) +
            'Size'.padEnd(colSize) +
            'Default'.padEnd(colDefault)
        );
        console.log('-'.repeat(colName + colLocation + colSize + colDefault));

        for (const f of all) {
            const name = f.name.length > colName - 2
                ? f.name.substring(0, colName - 4) + '..'
                : f.name;
            const sizeStr = `${f.size} B`;
            const defaultStr = f.isDefault ? 'yes' : '';

            console.log(
                name.padEnd(colName) +
                f.location.padEnd(colLocation) +
                sizeStr.padEnd(colSize) +
                defaultStr.padEnd(colDefault)
            );
        }

        console.log('');
        console.log(`Total: ${all.length} file(s)`);
        console.log('');
        console.log("Set a default with: npx restforge config set-default --config=<file>");
        console.log('');
    }
};
