const fs = require('fs');
const path = require('path');
const readline = require('readline');
const { padLeft } = require('src/utils/index.js');

const schemaDir = path.resolve(__dirname, '..', 'schemas');

(async () => {
  const args = process.argv.slice(2);
  let filename = args[0] || '';
  if (args.length === 0) {
    // use readline
    filename = await new Promise(resolve => {
      const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
      });

      rl.prompt();
      rl.question('schema filename: ', ans => {
        resolve(ans.replace(' ', '_'));

        rl.close();
      });

      rl.once('close', resolve);
    });
  }

  if (filename === '') throw new Error('no schema filename');

  const schemaFiles = await fs.promises.readdir(schemaDir);
  let version = 0;

  schemaFiles.forEach(name => {
    if (!name.endsWith('.sql')) return;

    const strInt = name.split(/_/g)[0];
    const v = parseInt(strInt, 10);
    if (isNaN(v)) return; // eslint-disable-line

    if (v > version) version = v;
  });

  // 版本要比最後一筆加一
  version += 1;

  const schemaName = `${padLeft(`${version}`, 6, '0')}_${filename}.sql`;

  const schemaText = `-- Created Time ${new Date().toISOString()}`;

  await fs.promises.writeFile(path.resolve(schemaDir, schemaName), schemaText, 'utf-8');

  console.info(`File: ${path.resolve(schemaDir, schemaName)} Created!`);
})().catch(err => {
  console.error(err);
  process.exit(1);
});
