import { writeFile } from 'fs/promises';

import { getArg } from './lib/args.js';
import { getChildDirectories } from './lib/io.js';
import { error, log } from './lib/log.js';

const ctx = 'initDb.js';

/**
 * Initializes a user db from a list of existing directories
 * at the specified `--path` parameter when executing the command.
 * Useful when there is already a collection of folders.
 */
export const initDb = async () => {
  log(ctx, 'Grabbing existing directories');
  let directory = '';
  try {
    directory = getArg('path');
  } catch (err) {
    error(ctx, err);
    return;
  }
  const children = await getChildDirectories(directory);
  const db = children.map(child => ({
    'user': child,
    'lastUpdated': 'never',
  }));
  log(ctx, 'Writing database');
  await writeFile(`${directory}/db.json`, JSON.stringify(db, null, 2));
  log(ctx, 'Writing complete!');
};

initDb();