const R = require("ramda");
const { TagsV1 } = require("@digiresilience/leafcutter-fields");
const {
  indexOfField,
  getFieldById,
  getFieldIds,
  getOptionsForField,
  getOptionIdsForField,
  getSubmitterFields,
  getAnalystFields,
} = require("@digiresilience/leafcutter-fields/src/fields");

const upTag = (name) => `Tag::Item.create(name: "${name}")`;

const downTag = (name) => `t = Tag::Item.find_by(name: "${name}")
  if !t.nil?
    t.destroy
  end
  `;

const upTagGroup = (field) =>
  R.map(upTag, getOptionIdsForField(TagsV1, field.id));
const downTagGroup = (field) =>
  R.map(downTag, getOptionIdsForField(TagsV1, field.id));

const upSection = (children) => `def self.up
  ${children.join("\n")}
end`;

const downSection = (children) => `def self.down
${children.join("\n")}
end`;

const migration = (
  name,
  ups,
  downs
) => `class ${name} < ActiveRecord::Migration[5.2]
${upSection(ups)}

${downSection(downs)}
end
`;

const ups = R.flatten(R.map(upTagGroup, TagsV1));
const downs = R.flatten(R.map(downTagGroup, TagsV1));

const name = process.argv[2];
if (!name) throw new Error("Must pass name of migration");

const re = RegExp("^[a-zA-Z][a-zA-Z0-9]+$");
if (!re.test(name))
  throw new Error("Name must be only alphanumeric and start with a letter");

const res = migration(name, ups, downs);
console.log(res);
