import { randomUUID } from 'crypto';
import { nexusEventBus } from '../../engines/event-bus.js';
import { insertRelayMessage, getRelayMessage } from '../worklist/crud.js';
export async function sendRelay(db, providers, knownTargets, input) {
    if (input.target === 'operative' && !knownTargets.has(input.toId)) {
        throw new Error(`[Architects] Unknown relay target operative ${input.toId}`);
    }
    const id = randomUUID();
    const message = insertRelayMessage(db, {
        id,
        fromOperativeId: input.fromOperativeId,
        toOperativeId: input.target === 'operative' ? input.toId : null,
        strikeTeamId: input.target === 'striketeam' ? input.toId : null,
        subject: input.subject,
        body: input.body,
        priority: input.priority ?? 'normal',
    });
    try {
        await providers.relay.publish('query', {
            content: JSON.stringify({ type: 'relay', target: input.target, toId: input.toId, subject: input.subject }),
            tags: ['#architects', '#relay', `#target:${input.target}`],
        });
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error);
        nexusEventBus.emit('architects.relay.failed', {
            messageId: message.id,
            from: input.fromOperativeId,
            target: input.target,
            toId: input.toId,
            subject: input.subject,
            error: reason,
        });
        throw new Error(`[Architects] Failed to publish relay message ${message.id}: ${reason}`);
    }
    nexusEventBus.emit('architects.relay.sent', {
        messageId: message.id,
        from: input.fromOperativeId,
        target: input.target,
        toId: input.toId,
        subject: input.subject,
    });
    return getRelayMessage(db, message.id);
}
