import { ServerMessageSchema } from '@pintrush/protocol';
import type { Socket } from 'socket.io';
import { log } from './logger';

/**
 * Every server→client message goes through here. In development and tests each envelope is checked
 * against the strict protocol schema (which also guards against leaking answers before reveal);
 * violations are logged and recorded so tests can assert there were none.
 */
export const outgoingViolations: { type: string; issue: string }[] = [];
let validate = false;

export function setOutgoingValidation(on: boolean): void {
  validate = on;
}

export function send(socket: Socket, type: string, envelope: Record<string, unknown>): void {
  if (validate) {
    const r = ServerMessageSchema.safeParse(envelope);
    if (!r.success) {
      const issue = r.error.issues
        .slice(0, 3)
        .map((i) => `${i.path.join('.')}: ${i.message}`)
        .join('; ');
      outgoingViolations.push({ type, issue });
      log.error('outgoing message failed protocol validation', { type, issue });
    }
  }
  socket.emit(type, envelope);
}
