import { saveAs } from 'file-saver';
import JSZip from 'jszip';

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

import {
  findClosestCommonDirectory,
  getCodeWalkthroughFileText,
  removeLeadingSlash,
} from '@redocly/theme/core/utils';

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

export async function downloadCodeWalkthrough(
  files: CodeWalkthroughFile[],
  state: Record<string, { value: string | boolean }>,
  inputsState: Record<string, { value: string }>,
) {
  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');
}
