import { beauty } from "./beauty";

export function getCodeList(
  template: string,
  codes: Record<string, string[] | undefined>,
) {
  const codeListRegex = /code_list:\s*\[([\s\S]*?)\]/;

  const match = template.match(codeListRegex);

  if (!match) {
    return template;
  }

  const tmpCodes: Record<string, any> = {}

  if (codes.naics.filter(Boolean).length) {
    tmpCodes.naics = codes.naics;
  }

  if (codes.psc.filter(Boolean).length) {
    tmpCodes.pcs = codes.psc;
  }

  if (Object.keys(tmpCodes).length === 0) {
    return template.replace(`[${match[1]}`, "[]");
  }

  const codeList = Object.entries(tmpCodes)
    .map(([key, value]) => {
      if (value) {
        return {
          title: key.toUpperCase(),
          list: value.map((item) => {
            const separators = ["–", "-", ":", "|", ";", ","];

            const regex = /[\s\-–:|;,]+/;

            let [code, ...descriptionParts] = item.split(regex);

            if (separators.includes(descriptionParts[0])) {
              descriptionParts.shift();
            }

            const description = descriptionParts.join(" ").trim();

            return [code, description];
          }),
        };
      }
      return false;
    })
    .filter(Boolean);
    
  template = template.replace(`[${match[1]}]`, beauty(codeList));

  return template;
}
