import { saveAs } from 'file-saver';

import type { CodeWalkthroughFile } from '@redocly/config';

import { removeLeadingSlash } from './urls';
import { findClosestCommonDirectory } from './find-closest-common-directory';
import { getCodeWalkthroughFileText } from './get-code-walkthrough-file-text';

export async function downloadCodeWalkthrough(
  files: CodeWalkthroughFile[],
  state: Record<string, { value: string | boolean }>,
  inputsState: Record<string, { value: string }>,
) {
  const JSZip = (await import('jszip')).default;

  // https://github.com/Stuk/jszip/issues/196#issuecomment-69503828
  JSZip.support.nodebuffer = false;

  const zip = new JSZip();

  const filePaths = files.map(({ path }) => path);
  const commonClosestDirectory = findClosestCommonDirectory(filePaths);

  for (const file of files) {
    const fileContent = getCodeWalkthroughFileText(file, state, inputsState);
    if (commonClosestDirectory === '/') {
      zip.file(file.path, fileContent);
    } else {
      const filePath = file.path.replace(removeLeadingSlash(`${commonClosestDirectory}/`), '');
      zip.file(filePath, fileContent);
    }
  }

  const zipContent = await zip.generateAsync({ type: 'blob' });
  saveAs(zipContent, 'sample-code.zip');
}
