import { randomUUID } from 'node:crypto';

import { validateConfig } from '@hexahost/config';

import { logger } from './logger';
import {
  publishNodeCommand,
  waitForNodeResponse,
  type NodeResponseMessage,
} from './redis';

export interface AgentRequestResult extends NodeResponseMessage {
  result?: unknown;
}

export async function sendAgentRequest(
  nodeId: string,
  type: string,
  payload: Record<string, unknown>,
  timeoutMs = 120_000,
): Promise<AgentRequestResult> {
  const messageId = randomUUID();

  await publishNodeCommand({
    nodeId,
    envelope: {
      protocolVersion: 1,
      messageId,
      type,
      timestamp: new Date().toISOString(),
      payload: {
        ...payload,
        generation: payload['generation'] ?? 0,
      },
    },
  });

  const response = await waitForNodeResponse(messageId, timeoutMs);

  if (response === null) {
    logger.error({ nodeId, type, messageId }, 'Agent request timed out');
    return {
      success: false,
      errorCode: 'AGENT_TIMEOUT',
      errorMessage: 'Agent request timed out',
    };
  }

  return response as AgentRequestResult;
}

export function loadStorageEnv(): void {
  validateConfig();
}
