export const scriptTypes = ['seed', 'migration'] as const;

type ScriptType = (typeof scriptTypes)[number];

/**
 * Generates the name of a script file, excluding the file extension and the
 * ordering-related prefixes added by umzug. This function enforces a convention
 * that allows us to identify whether a script is a seed and, if so, which
 * environment it should run in.
 *
 * @param type - Whether this is a migration or seed
 * @param env - If a seed, which environment the seed applies to.
 * @param userNamePortion - The portion of the name provided by the user to
 *   actually describe what the script does.
 */
export function nameScript(
  type: ScriptType,
  env: string | undefined,
  userNamePortion: string,
) {
  return `${userNamePortion}${type === 'seed' ? `.seed.${env}` : ''}`;
}

/**
 * Returns whether the given script, based on its name as generated by
 * {@see nameScript}, should run in the given environment.
 */
export function shouldRun(
  env: string,
  legalScriptFormats: readonly string[],
  scriptName: string,
) {
  const anyEnvSeedFileRegex = new RegExp(
    `\\.seed\\.[^\\.]+\\.(${legalScriptFormats.join('|')})$`,
  );
  const thisEnvSeedFileRegex = new RegExp(
    `\\.seed\\.${env}\\.(${legalScriptFormats.join('|')})$`,
  );

  const isSeed = anyEnvSeedFileRegex.test(scriptName);
  return !isSeed || thisEnvSeedFileRegex.test(scriptName);
}
