#!/usr/bin/env node

import { promises as fs } from "fs";
import path from "path";

const underscore = (str: string) => {
  return str
    .replace(/([a-z\d])([A-Z])/g, "$1_$2")
    .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1_$2")
    .toLowerCase();
}

const camelize = (str: string): string => {
  const camelizedStr = str.replace(/_([a-z])/g, (g) => g[1].toUpperCase());

  return camelizedStr.charAt(0).toUpperCase() + camelizedStr.slice(1);
}

export const createMigration = async ({ displayName }: Record<string, string>) => {
  const rawName: string = await new Promise((resolve) => {
    process.stdin.setEncoding("utf-8");
    process.stdout.write("Enter migration name: ");
    process.stdin.once("data", (data: string) => {
      resolve(data.trim());
    });
  });

  const migrationBaseName = `${displayName}_${underscore(rawName)}`;
  const migrationName = camelize(migrationBaseName);
  const migrationTemplate = `class MIGRATION_NAME < ActiveRecord::Migration[5.2]
    def self.up
      # add your code here
    end

    def self.down
      # add your code here
    end
  end`;
  const contents = migrationTemplate.replace("MIGRATION_NAME", migrationName);
  const time = new Date().toISOString().replace(/[-:.]/g, "").slice(0, 14);
  const migrationFileName = `${time}_${migrationBaseName}.rb`;
  const addonDir = path.join("src", "db", "addon", displayName);
  await fs.mkdir(addonDir, { recursive: true });
  await fs.writeFile(path.join(addonDir, migrationFileName), contents);
}

const main = async () => {
  const packageJSON = JSON.parse(await fs.readFile("./package.json", "utf-8"));
  const { displayName } = packageJSON;
  await createMigration({ displayName });
}

main();
