import { readFile } from 'node:fs/promises';
import { join } from 'node:path';

export const TEST_PLUGIN_FIXTURE_DIR = join(__dirname, '..', 'fixtures', 'plugins', 'api-test-plugin');
export const TEST_PLUGIN_ID = 'e2e.plugin-api';
export const TEST_PLUGIN_RELAY_EVENT = 'e2e:relay';
export const TEST_PLUGIN_P2P_EVENT = 'e2e:p2p';

export interface PluginApiTestManifestEvent {
  direction: 'clientToServer' | 'serverRelay' | 'p2pHint';
  eventName: string;
  maxPayloadBytes?: number;
  scope: 'server' | 'channel' | 'user' | 'plugin';
}

export interface PluginApiTestManifest {
  description: string;
  events: PluginApiTestManifestEvent[];
  id: string;
  title: string;
  version: string;
}

export async function readPluginApiTestManifest(): Promise<PluginApiTestManifest> {
  const manifestPath = join(TEST_PLUGIN_FIXTURE_DIR, 'toju-plugin.json');
  const manifestText = await readFile(manifestPath, 'utf8');

  return JSON.parse(manifestText) as PluginApiTestManifest;
}

export function getPluginApiTestEvent(
  manifest: PluginApiTestManifest,
  eventName: string
): PluginApiTestManifestEvent {
  const eventDefinition = manifest.events.find((event) => event.eventName === eventName);

  if (!eventDefinition) {
    throw new Error(`Expected fixture plugin to define ${eventName}`);
  }

  return eventDefinition;
}
