/**
 * Copyright Super iPaaS Integration LLC, an IBM Company 2024
 */
import { isYamlFile } from "../common/fs-helper.js";
import AdmZip from "adm-zip";
import { readMultiYaml } from "../common/yaml-helper.js";
import { BaseAsset } from "../../model/assets-model.js";
import { isValidAsset } from "./asset-helper.js";
import { showInfo, showWarning } from "../common/message-helper.js";
import { AssetCache } from "../../cache/asset-cache.js";
import { getRefsFromAsset } from "../../handlers/asset-handler.js";
import { DebugManager } from "../../debug/debug-manager.js";
import {
  AND_REF,
  CHECKING_DEPENDENCY,
  DEPENDENCY_IDENTIFIED,
  INVALID_ASSET,
  KIND,
  LINE,
  NAME,
  NO_DEPENDENCY_FOUND,
  SKIPPED,
} from "../../constants/message-constants.js";

const loadCacheWithProject = (zipFile: AdmZip) => {
  const zipEntries = zipFile.getEntries();
  zipEntries.forEach((entry) => {
    if (entry.isDirectory) {
      return;
    }
    if (!isYamlFile(entry.entryName)) {
      return;
    }
    const assets = readMultiYaml<BaseAsset>(entry.entryName, entry.getData().toString("utf-8"));

    for (const asset of assets) {
      if (!isValidAsset(asset)) {
        if (DebugManager.getInstance().isDebugEnabled()) {
          showWarning(
            `${INVALID_ASSET} ${KIND}-${asset.kind} ${NAME}-${asset.metadata?.name} - ${SKIPPED}`
          );
          showWarning(`${JSON.stringify(asset).substring(0, 25)}...`);
        }
        continue;
      }
      AssetCache.getInstance().markAsProcessed(asset);
      checkForDependencyAssets(asset);
    }
  });
};

const checkForDependencyAssets = (asset: BaseAsset) => {
  if (DebugManager.getInstance().isDebugEnabled()) {
    showInfo(`\n\n${LINE}`);
    showInfo(
      `${CHECKING_DEPENDENCY} - '${asset.kind}' and ref - '${asset.metadata.name}' `
    );
    showInfo(LINE);
  }
  const refsFromAsset = getRefsFromAsset(asset);

  refsFromAsset.forEach((assetCacheModel) => {
    if (DebugManager.getInstance().isDebugEnabled()) {
      showInfo(
        `${DEPENDENCY_IDENTIFIED} ${KIND} - '${assetCacheModel.kind}' ${AND_REF} - '${assetCacheModel.ref}' `
      );
    }
    assetCacheModel.isNewlyAdded = true;
    AssetCache.getInstance().checkAndMarkAsUnProcessed(assetCacheModel);
  });

  if (
    refsFromAsset.length === 0 &&
    DebugManager.getInstance().isDebugEnabled()
  ) {
    showInfo(
      `${NO_DEPENDENCY_FOUND} - '${asset.kind}' ${AND_REF} - '${asset.metadata.name}'\n\n`
    );
  }
};

export { loadCacheWithProject, checkForDependencyAssets };
