'use strict';

/**
 * Contract: project list
 *
 * Menampilkan daftar project yang terdaftar di registry
 * (.restforge/projects.json). Tidak menerima flag.
 *
 * Inline migration v4.0.0: business logic asli dari
 * `list-projects.js` (function `listProjectsMain`) di-inline langsung
 * di handler. Adapter `process.argv` override sudah dihapus karena handler
 * tidak lagi memerlukan argv translation.
 */

const projectRegistry = require('../../lib/utils/project-registry');

module.exports = {
    resource: 'project',
    verb: 'list',
    description: 'Menampilkan daftar project yang terdaftar di registry',
    category: 'management',
    flags: {},
    examples: [
        'npx restforge project list'
    ],
    async handler(_args) {
        const projects = projectRegistry.getProjectList();

        if (projects.length === 0) {
            console.log('');
            console.log('No projects registered yet.');
            console.log('');
            console.log('Use "npx restforge endpoint create" to create a new project.');
            console.log('');
            return;
        }

        const colName = 20;
        const colDb = 12;
        const colEndpoints = 40;
        const colCreated = 12;

        console.log('');
        console.log('Registered Projects:');
        console.log('');
        console.log(
            'Project Name'.padEnd(colName) +
            'Database'.padEnd(colDb) +
            'Endpoints'.padEnd(colEndpoints) +
            'Created'.padEnd(colCreated)
        );
        console.log('-'.repeat(colName + colDb + colEndpoints + colCreated));

        for (const project of projects) {
            const name = project.name.length > colName - 2
                ? project.name.substring(0, colName - 4) + '..'
                : project.name;
            const endpoints = project.endpoints.length > colEndpoints - 2
                ? project.endpoints.substring(0, colEndpoints - 4) + '..'
                : project.endpoints;

            console.log(
                name.padEnd(colName) +
                project.database.padEnd(colDb) +
                endpoints.padEnd(colEndpoints) +
                project.createdAt.padEnd(colCreated)
            );
        }

        console.log('');
        console.log(`Total: ${projects.length} project(s)`);
        console.log('');
    }
};
