'use strict';

/**
 * Contract: schema init
 *
 * Thin wrapper untuk scaffold file schema definition. Implementasi sekarang
 * mendelegasikan ke binary native sdf-tools.exe dengan template `dummy`,
 * menggantikan generator skeleton custom yang sebelumnya inline.
 *
 * Setara dengan: sdf-tools.exe --table=dummy --generate --lang=sdf --path=<USER_PATH>
 *
 * Kontrak CLI dipertahankan (verb, category, flag --path) agar workflow user
 * tidak breaking. File yang dihasilkan berisi struktur template `dummy` dari
 * koleksi RestForge Schema Reference, yang dapat di-rename dan diadaptasi
 * sesuai kebutuhan.
 */

const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawnSync } = require('child_process');

function resolveBinaryPath() {
    if (os.platform() !== 'win32') return null;
    return path.resolve(__dirname, '..', '..', '..', 'bin', 'sdf-tools.exe');
}

module.exports = {
    resource: 'schema',
    verb: 'init',
    description: 'Membuat skeleton file schema definition (delegate ke sdf-tools dengan template dummy)',
    category: 'utility',
    flags: {
        path: {
            type: 'string',
            required: true,
            description: 'Path file schema yang akan dibuat (mis. schema/users.js)'
        }
    },
    examples: [
        'npx restforge schema init --path=schema/users.js',
        'npx restforge schema init --path=./schema/item_product.js'
    ],
    async handler(args) {
        if (!args.path) {
            console.error('Error: Target file path is required.');
            console.error("Run 'npx restforge schema init --help' for usage information");
            throw new Error('Target file path is required');
        }

        const binaryPath = resolveBinaryPath();
        if (!binaryPath) {
            const err = new Error(
                `schema init hanya tersedia di Windows (sdf-tools.exe). Platform saat ini: ${os.platform()}`
            );
            err.exitCode = 3;
            throw err;
        }

        if (!fs.existsSync(binaryPath)) {
            const err = new Error(
                `sdf-tools.exe tidak ditemukan di ${binaryPath}. ` +
                'Pastikan binary sudah di-build dan tersedia di folder bin/ package.'
            );
            err.exitCode = 3;
            throw err;
        }

        const binaryArgs = [
            '--table=dummy',
            '--generate',
            '--lang=sdf',
            `--path=${args.path}`
        ];

        const result = spawnSync(binaryPath, binaryArgs, {
            stdio: 'inherit',
            windowsHide: true
        });

        if (result.error) {
            const err = new Error(`Gagal menjalankan sdf-tools.exe: ${result.error.message}`);
            err.exitCode = 1;
            throw err;
        }

        const status = typeof result.status === 'number' ? result.status : 1;
        if (status !== 0) {
            const err = new Error(`sdf-tools.exe exit code ${status}`);
            err.exitCode = status;
            err.silent = true;
            throw err;
        }
    }
};
