/**
 * Project Registry Utility
 *
 * Mengelola registry project yang terdaftar di working directory.
 * Registry disimpan di {cwd}/.restforge/projects.json.
 *
 * @module project-registry
 */

const fs = require('fs');
const path = require('path');

// Path ke registry file
const REGISTRY_DIR = path.join(process.cwd(), '.restforge');
const REGISTRY_PATH = path.join(REGISTRY_DIR, 'projects.json');

/**
 * Load project registry dari file.
 * Jika file belum ada, return object kosong dan buat file.
 *
 * @returns {{ projects: Object }} Registry object
 */
function loadProjectRegistry() {
    try {
        if (!fs.existsSync(REGISTRY_PATH)) {
            const emptyRegistry = { projects: {} };
            saveProjectRegistry(emptyRegistry);
            return emptyRegistry;
        }

        const content = fs.readFileSync(REGISTRY_PATH, 'utf-8');
        const registry = JSON.parse(content);

        // Pastikan struktur valid
        if (!registry.projects || typeof registry.projects !== 'object') {
            registry.projects = {};
        }

        return registry;
    } catch (error) {
        // Jika file corrupt, return empty dan overwrite
        console.warn(`Warning: Registry file is corrupt or unreadable. Creating a new registry.`);
        const emptyRegistry = { projects: {} };
        saveProjectRegistry(emptyRegistry);
        return emptyRegistry;
    }
}

/**
 * Simpan project registry ke file.
 *
 * @param {{ projects: Object }} registry - Registry object untuk disimpan
 */
function saveProjectRegistry(registry) {
    try {
        if (!fs.existsSync(REGISTRY_DIR)) {
            fs.mkdirSync(REGISTRY_DIR, { recursive: true });
        }

        fs.writeFileSync(REGISTRY_PATH, JSON.stringify(registry, null, 2), 'utf-8');
    } catch (error) {
        console.error(`Error: Gagal menyimpan registry ke ${REGISTRY_PATH}`);
        console.error(`Detail: ${error.message}`);
    }
}

/**
 * Register atau update project di registry.
 * Jika project sudah ada, endpoint di-append (tanpa duplikat).
 * Jika project belum ada, dibuat entry baru.
 *
 * @param {string} projectName - Nama project
 * @param {string} database - Tipe database (postgres, oracle, mysql)
 * @param {string} endpoint - Nama endpoint yang digenerate
 */
function registerProject(projectName, database, endpoint) {
    const registry = loadProjectRegistry();

    if (registry.projects[projectName]) {
        // Update existing project
        const project = registry.projects[projectName];

        // Update database type jika diberikan
        if (database) {
            project.database = database;
        }

        // Append endpoint tanpa duplikat
        if (endpoint && !project.endpoints.includes(endpoint)) {
            project.endpoints.push(endpoint);
        }
    } else {
        // Buat entry baru
        registry.projects[projectName] = {
            database: database || 'postgres',
            createdAt: new Date().toISOString(),
            endpoints: endpoint ? [endpoint] : []
        };
    }

    saveProjectRegistry(registry);
}

/**
 * Ambil daftar project untuk ditampilkan sebagai tabel.
 *
 * @returns {Array<{ name: string, database: string, endpoints: string, createdAt: string }>}
 */
function getProjectList() {
    const registry = loadProjectRegistry();
    const list = [];

    for (const [name, info] of Object.entries(registry.projects)) {
        list.push({
            name,
            database: info.database || '-',
            endpoints: (info.endpoints || []).join(', ') || '-',
            createdAt: info.createdAt ? info.createdAt.substring(0, 10) : '-'
        });
    }

    return list;
}

module.exports = {
    loadProjectRegistry,
    saveProjectRegistry,
    registerProject,
    getProjectList,
    REGISTRY_PATH
};
