import {readFile, readdir} from 'fs/promises';
import url from 'url';
import path from 'path';

/**
 * @example version(1, import.meta.url)
 * @param options {Omit<import('@openstapps/core').SCAppVersionInfo, 'releaseNotes' | 'translations'>}
 * @param base {string}
 * @returns {Promise<import('@openstapps/core').SCAppVersionInfo>}
 */
export async function version(options, base) {
  const de = await readFile(new URL(`${options.version}.de.md`, base), 'utf8');
  const en = await readFile(new URL(`${options.version}.en.md`, base), 'utf8');

  return {
    ...options,
    releaseNotes: de,
    translations: {
      en: {
        releaseNotes: en,
      },
    },
  };
}

/**
 * @param base {string} Base path of the file as `import.meta.url`
 * @returns {Promise<import('@openstapps/core').SCAppVersionInfo[]>}
 */
export async function versions(base) {
  const directory = await readdir(path.dirname(url.fileURLToPath(base)));
  const versions = [
    ...new Set(directory.filter(it => it.endsWith('.md')).map(it => it.replace(/\.\w+\.md$/, ''))),
  ].sort((a, b) => -a.localeCompare(b, undefined, {numeric: true}));

  return Promise.all(versions.map(versionName => version({version: versionName}, base)));
}
