import { resolveNpmPath } from '../../common/index.js';
import { appConfig } from '../../config/app.js';
import { Logger } from '../../config/logger.js';
import { execFileSync } from '../../node-singletons/child-process.js';
const runWrangler = (args, cmd) => {
    const npmPath = resolveNpmPath();
    const printable = `npm exec --yes -- wrangler ${args.join(' ')}`;
    if (cmd) {
        cmd.debug(`Executing: ${printable}`);
    }
    else {
        Logger.debug(`[WranglerD1] Executing: ${printable}`);
    }
    return execFileSync(npmPath, ['exec', '--yes', '--', 'wrangler', ...args], {
        stdio: 'pipe',
        encoding: 'utf8',
        env: appConfig.getSafeEnv(),
    });
};
export const WranglerD1 = Object.freeze({
    applyMigrations(opts) {
        const args = ['d1', 'migrations', 'apply', opts.dbName, opts.isLocal ? '--local' : '--remote'];
        return runWrangler(args, opts.cmd);
    },
    executeSql(opts) {
        const args = [
            'd1',
            'execute',
            opts.dbName,
            opts.isLocal ? '--local' : '--remote',
            '--command',
            opts.sql,
        ];
        return runWrangler(args, opts.cmd);
    },
});
