'use strict';

/**
 * Contract: schema models
 *
 * List semua model dari folder schema dengan ringkasan struktur (jumlah field,
 * jenis primary key, jumlah index, unique, dan relation). Tidak menjalankan
 * cross-model validation.
 *
 * Inline migration v4.0.0: business logic dari dbschema-models.js
 * dipindah ke handler.
 */

const path = require('path');
const { loadSchemaPath } = require('../../lib/dbschema-kit/loader');

const COL_SCHEMA = 12;
const COL_TABLE = 25;
const COL_FIELDS = 8;
const COL_PK = 11;
const COL_INDEXES = 9;
const COL_UNIQUES = 9;
const COL_RELATIONS = 9;

const SCHEMA_PLACEHOLDER = '-';

function formatPk(primaryKey) {
    if (!Array.isArray(primaryKey) || primaryKey.length === 0) return 'none';
    if (primaryKey.length === 1) return 'single';
    return `composite (${primaryKey.length})`;
}

function printRow(values) {
    const widths = [COL_SCHEMA, COL_TABLE, COL_FIELDS, COL_PK, COL_INDEXES, COL_UNIQUES, COL_RELATIONS];
    let line = '';
    for (let i = 0; i < values.length; i++) {
        line += String(values[i]).padEnd(widths[i]);
    }
    console.log(line.trimEnd());
}

function printDivider() {
    const widths = [COL_SCHEMA, COL_TABLE, COL_FIELDS, COL_PK, COL_INDEXES, COL_UNIQUES, COL_RELATIONS];
    let line = '';
    for (const w of widths) {
        line += '-'.repeat(Math.max(0, w - 2)).padEnd(w);
    }
    console.log(line.trimEnd());
}

function sortModels(models) {
    const entries = [...models.entries()];
    entries.sort((a, b) => {
        const aSchema = a[1].schemaName || null;
        const bSchema = b[1].schemaName || null;
        if (aSchema === null && bSchema !== null) return 1;
        if (aSchema !== null && bSchema === null) return -1;
        if (aSchema !== bSchema) return aSchema < bSchema ? -1 : 1;
        const aTable = a[1].tableName;
        const bTable = b[1].tableName;
        if (aTable === bTable) return 0;
        return aTable < bTable ? -1 : 1;
    });
    return entries;
}

module.exports = {
    resource: 'schema',
    verb: 'models',
    description: 'Menampilkan daftar schema models dengan ringkasan struktur (fields, primary key, indexes, uniques, relations)',
    category: 'introspection',
    flags: {
        path: {
            type: 'string',
            required: true,
            description: 'Path file atau folder schema (mis. ./schema atau ./schema/users.js)'
        }
    },
    examples: [
        'npx restforge schema models --path=./schema',
        'npx restforge schema models --path=./custom-schema'
    ],
    async handler(args) {
        const schemaPath = args.path;
        const absPath = path.resolve(process.cwd(), schemaPath);

        let models;
        try {
            models = loadSchemaPath(absPath);
        } catch (err) {
            console.error(`Error: ${err.message}`);
            throw err;
        }

        printRow(['Schema', 'Table', 'Fields', 'PK', 'Indexes', 'Uniques', 'Relations']);
        printDivider();

        for (const [, ir] of sortModels(models)) {
            const fieldCount = ir.fields ? Object.keys(ir.fields).length : 0;
            const indexCount = Array.isArray(ir.indexes) ? ir.indexes.length : 0;
            const uniqueCount = Array.isArray(ir.uniques) ? ir.uniques.length : 0;
            const relationCount = ir.relations ? Object.keys(ir.relations).length : 0;
            printRow([
                ir.schemaName || SCHEMA_PLACEHOLDER,
                ir.tableName,
                fieldCount,
                formatPk(ir.primaryKey),
                indexCount,
                uniqueCount,
                relationCount
            ]);
        }

        console.log('');
        console.log(`${models.size} models loaded.`);
    }
};
