/**
 * Copyright IBM Corp. 2024, 2025
 */

import { Test, TestSchema } from '../schemas/test.schema.js';
import { VCM } from '../engine/variable-context-manager/context-manager.js';
import { transformZodErrors } from '../helpers/zod-error-formatter.helper.js';

export class TestFactory {
  create(test: any): Test {
    let parsed;
    try {
      // Filter out skipped requests before parsing so that they are not processed and also zod validation do not apply to them
      if (test.spec?.request) {
        test.spec.request = test.spec.request.filter(
          (request: any) => !request.skipped,
        );
      }
      parsed = TestSchema.parse(test);
    } catch (error) {
      throw transformZodErrors(error);
    }
    const vcmId = crypto.randomUUID();
    const model = {
      kind: parsed.kind,
      metadata: parsed.metadata,
      spec: parsed.spec,
      vcmId,
    };
    // Handle environment which can be either a single object or an array
    let variables: any[] = [];
    if (parsed.spec.environment) {
      if (Array.isArray(parsed.spec.environment)) {
        // If it's an array, collect variables from all environment objects
        variables = parsed.spec.environment.flatMap(
          (env) => env?.variables || [],
        );
      } else {
        // If it's a single object, use its variables
        variables = parsed.spec.environment.variables || [];
      }
    }
    VCM.loadEnv(vcmId, variables);
    return model;
  }
}
