'use strict';

/**
 * Contract: catalog dbschema
 *
 * Output JSON catalog dbschema-kit defineModel API spec (field types,
 * constraints, relations, shorthand syntax, naming rules, dialect support).
 *
 * Inline migration v4.0.0: business logic asli dari dbschema-catalog.js
 * di-inline langsung di handler. Adapter argv override dihapus, handler pakai
 * args.section/name/kind/pretty langsung. Filter & validation logic dipertahankan
 * untuk menjaga snapshot regression dan behavior yang ter-expose.
 */

const { DBSCHEMA_CATALOG } = require('../../lib/templates/dbschema-catalog');

const VALID_SECTIONS = [
    'defineModelOptions',
    'fieldTypes',
    'constraints',
    'relationTypes',
    'referentialActions',
    'checkOperations',
    'auditColumns',
    'shorthandSyntax',
    'namingRules',
    'dialectSupport'
];

const FILTER_DEFS = [
    {
        flag: '--name', key: 'name', validSections: [
            'defineModelOptions',
            'fieldTypes',
            'constraints',
            'relationTypes',
            'referentialActions',
            'checkOperations',
            'dialectSupport'
        ]
    },
    { flag: '--kind', key: 'kind', validSections: ['constraints'] }
];

function validateFilters(section, filters) {
    if (section !== null && !VALID_SECTIONS.includes(section)) {
        console.error(`Error: Invalid --section value '${section}'`);
        console.error(`Valid sections: ${VALID_SECTIONS.join(', ')}`);
        throw new Error(`Invalid --section value '${section}'`);
    }

    const activeFilters = Object.keys(filters).filter(k => filters[k] !== null && filters[k] !== undefined);

    if (activeFilters.length > 0 && !section) {
        const flagList = activeFilters.map(k => {
            const def = FILTER_DEFS.find(d => d.key === k);
            return def ? def.flag : '--' + k;
        }).join(', ');
        console.error(`Error: Filter ${flagList} requires --section`);
        throw new Error(`Filter ${flagList} requires --section`);
    }

    for (const filterKey of activeFilters) {
        const def = FILTER_DEFS.find(d => d.key === filterKey);
        if (!def) continue;
        if (!def.validSections.includes(section)) {
            const validList = def.validSections.map(s => `--section=${s}`).join(', ');
            console.error(`Error: ${def.flag} is only valid with one of: ${validList}`);
            throw new Error(`${def.flag} is only valid with one of: ${validList}`);
        }
    }
}

function applyFilters(items, filters) {
    let result = items;

    if (filters.name) {
        result = result.filter(item => item.name === filters.name);
    }
    if (filters.kind) {
        result = result.filter(item => item.kind === filters.kind);
    }

    return result;
}

function buildFilteredOutput(section, filters) {
    const sectionData = DBSCHEMA_CATALOG[section];
    const activeFilters = {};
    for (const [k, v] of Object.entries(filters)) {
        if (v !== null && v !== undefined) activeFilters[k] = v;
    }
    const hasFilters = Object.keys(activeFilters).length > 0;

    const summary = {
        section,
        filtered: hasFilters
    };
    if (hasFilters) {
        summary.filters = { ...activeFilters };
    }

    let payload;
    if (Array.isArray(sectionData)) {
        const filtered = hasFilters ? applyFilters(sectionData, activeFilters) : sectionData;
        summary.totalCount = sectionData.length;
        summary.matchedCount = filtered.length;
        payload = filtered;
    } else {
        payload = sectionData;
    }

    return {
        schemaVersion: DBSCHEMA_CATALOG.schemaVersion,
        source: DBSCHEMA_CATALOG.source,
        summary,
        [section]: payload
    };
}

module.exports = {
    resource: 'catalog',
    verb: 'dbschema',
    description: 'Output JSON catalog dbschema-kit defineModel API spec (field types, constraints, relations, shorthand syntax, naming rules)',
    category: 'introspection',
    flags: {
        section: {
            type: 'string',
            required: false,
            default: null,
            description: 'Filter berdasarkan section (defineModelOptions, fieldTypes, constraints, relationTypes, referentialActions, checkOperations, auditColumns, shorthandSyntax, namingRules, dialectSupport)'
        },
        name: {
            type: 'string',
            required: false,
            default: null,
            description: 'Filter berdasarkan nama exact (hanya valid bersama --section untuk array sections)'
        },
        kind: {
            type: 'string',
            required: false,
            default: null,
            description: 'Filter constraint berdasarkan kind: standalone atau value (hanya valid dengan --section=constraints)'
        },
        pretty: {
            type: 'boolean',
            required: false,
            default: true,
            description: 'Pretty-print output JSON'
        }
    },
    examples: [
        'npx restforge catalog dbschema',
        'npx restforge catalog dbschema --section=fieldTypes',
        'npx restforge catalog dbschema --section=fieldTypes --name=string',
        'npx restforge catalog dbschema --section=constraints --kind=standalone'
    ],
    async handler(args) {
        const pretty = args.pretty !== false;
        const section = args.section || null;
        const filters = {
            name: args.name || null,
            kind: args.kind || null
        };

        validateFilters(section, filters);

        const output = section
            ? buildFilteredOutput(section, filters)
            : DBSCHEMA_CATALOG;

        const json = pretty
            ? JSON.stringify(output, null, 2)
            : JSON.stringify(output);
        console.log(json);
    }
};
