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

import { processProjectBuild, processGatewayJson } from '../../src/index.js';
import fs from 'fs';
import path from 'path';
import { Logger } from '@apic/studio-shared';

jest.mock('@apic/studio-shared', () => ({
  Logger: {
    debug: jest.fn(),
    info: jest.fn(),
    warn: jest.fn(),
    error: jest.fn(),
    log: jest.fn(),
  },
  LogComponent: () => (target: any) => target,
  Component: {
    Build: 'Build',
  },

  ErrorResponse: jest.fn(),
  Metadata_Ref: jest.fn(),
  SpecObject: jest.fn(),
  YamlContent: jest.fn(),
  UpperCaseKinds: jest.fn(),
  loadYaml: jest.fn((content) => require('js-yaml').load(content)),

  SchemaHandler: jest.fn().mockImplementation(() => ({
    getSchema: jest.fn().mockReturnValue(JSON.stringify({ type: 'object' })),
  })),
}));

jest.mock('@apic/studio-client-model', () => ({
  AssetModelKindConstants: {
    API: 'API',
  },
}));

describe('processBuild', () => {
  it('should handle processGatewayJson', async () => {
    const zipFilePath = path.resolve(__dirname, '../assets/gateway-multi-project-asset.zip');
    const zipBuffer = fs.readFileSync(zipFilePath);

    const res = await processGatewayJson(zipBuffer);
    expect(res).not.toBeNull;
  });

  it('should handle error in processing Project zip', async () => {
    const zipFilePath = path.resolve(__dirname, '../assets/gateway-asset-error.zip');
    const zipBuffer = fs.readFileSync(zipFilePath);

    const result = await processProjectBuild(zipBuffer, 'apim');

    expect(result.success).toBe(false);
    expect(result.statusCode).toBe(400);
    expect(result.message).toBe('Project build validation failed');
    expect(result.data).toBeNull();
    expect(result.errors[0]).toMatch(/Review the error and try publishing again/);
  });

  it('should handle error in processing Project zip successful', async () => {
    const zipFilePath = path.resolve(__dirname, '../assets/gateway-multi-project-asset.zip');
    const zipBuffer = fs.readFileSync(zipFilePath);
    await processProjectBuild(zipBuffer, 'apim');
    expect(Logger.info).toHaveBeenCalledWith('Starting project build processing.');
  });
});
