/**
 * Copyright Super iPaaS Integration LLC, an IBM Company 2024
 */
import { APIAsset, RefModel, BaseAsset } from "../model/assets-model.js";
import { checkForNullOrUndefined } from "../helpers/common/data-helper.js";
import { showWarning } from "../helpers/common/message-helper.js";
import { AssetCacheModel } from "../model/asset-cache-model.js";
import { KindEnums } from "@apic/api-model/common/StudioEnums.js";

const getRefsFromApiAsset = (asset: BaseAsset): AssetCacheModel[] => {
  const apiAsset = asset as unknown as APIAsset;
  const dependentAssets: AssetCacheModel[] = [];

  const dependentPolicySequenceAssets = checkPolicySequence(apiAsset);
  dependentAssets.push(...dependentPolicySequenceAssets);

  return dependentAssets;
};

const getAPIDefPath = (asset: BaseAsset): string | undefined => {
  const apiAsset = asset as unknown as APIAsset;
  const spec = checkForNullOrUndefined(
    apiAsset.spec,
    `Spec is not defined for the asset with kind 'API' and name '${apiAsset.metadata?.name}'`
  );
  const apiSpec = checkForNullOrUndefined(
    spec["api-spec"],
    `Attribute 'api-spec' is not defined
	for kind 'API' and name '${apiAsset.metadata?.name}'`
  );
  return apiSpec.$path;
};

const checkPolicySequence = (apiAsset: APIAsset): AssetCacheModel[] => {
  let spec = null;
  try {
    spec = checkForNullOrUndefined(
      apiAsset.spec,
      `Spec is not defined for the asset with kind 'API' and name '${apiAsset.metadata?.name}'`
    );
  } catch (error: unknown) {
    showWarning((error as Error).message);
    return [];
  }
  const policySeq: RefModel[] = spec["policy-sequence"];
  return policySeq.map((pSeq) => {
    return {
      kind: KindEnums.PolicySequence,
      ref: pSeq.$ref,
      isNewlyAdded: true,
    };
  });
};

export { getRefsFromApiAsset, getAPIDefPath };
