import {
  BaseAsset,
  RefObj,
  TestAsset,
  TestSpec,
} from "../../../model/assets-model.js";
import {
  checkForNullOrUndefined,
  isNullOrUndefined,
} from "../../common/data-helper.js";
import { AssetCacheModel } from "../../../model/asset-cache-model.js";
import { showError } from "./../../common/message-helper.js";
import { KindEnums } from "@apic/api-model/common/StudioEnums.js";

const addAssetRefValuesForTestKind = (
  refObjects: RefObj[],
  result: AssetCacheModel[],
  kind: KindEnums
) => {
  if (!isNullOrUndefined(refObjects)) {
    refObjects.forEach((refObj) => {
      if (!isNullOrUndefined(refObj.$ref)) {
        result.push({
          kind,
          ref: refObj.$ref,
          isNewlyAdded: true });
      }
    });
  }
};

const getRefsFromTestAsset = (asset: BaseAsset): AssetCacheModel[] => {
  const testAsset = asset as unknown as TestAsset;
  const spec: TestSpec = testAsset.spec;
  const result: AssetCacheModel[] = [];
  try {
    checkForNullOrUndefined(testAsset, "Asset is null or undefined");
    if (spec.environment?.$ref) {
      addAssetRefValuesForTestKind(
        [{ $ref: spec.environment.$ref }],
        result,
        KindEnums.Environment
      );
    }
    if (spec.request) {
      spec.request.forEach((request) => {
        if (request.assertions) {
          if (request.assertions.$ref) {
            addAssetRefValuesForTestKind(
              [{ $ref: request.assertions.$ref }],
              result,
              KindEnums.Assertion
            );
          }
        }
      });
    }
    return result;
  } catch (error: unknown) {
    showError((error as Error).message);
    return [];
  }
};

export { getRefsFromTestAsset };
