#!/usr/bin/env node

const { spawnSync } = require('child_process');

const args = process.argv.slice(2);
let migrationName = null;

for (let i = 0; i < args.length; i += 1) {
  const arg = args[i];
  if (arg === '-n' || arg === '--name') {
    migrationName = args[i + 1] || null;
    break;
  }
}

if (!migrationName) {
  process.stderr.write(
    'Please provide a migration name, e.g. npm run migration:generate -- -n update_member_table\n',
  );
  process.exit(1);
}

const fileName = migrationName
  .trim()
  .replace(/\s+/g, '_')
  .replace(/[^a-zA-Z0-9_-]/g, '');

if (!fileName) {
  process.stderr.write('Migration name is invalid after sanitization.\n');
  process.exit(1);
}

const cliArgs = [
  'typeorm-ts-node-commonjs',
  'migration:generate',
  `src/migrations/${fileName}`,
  '-d',
  'src/config/database/migration.datasource.ts',
];

const result = spawnSync('npx', cliArgs, {
  stdio: 'inherit',
  shell: false,
});

if (typeof result.status === 'number') {
  process.exit(result.status);
}

process.exit(1);
