/**
 * Discord Outreach Publisher
 *
 * Publishes outreach messages drafted by the contributor pipeline to Discord
 * via the Discord REST API directly (no SDK — one POST endpoint per message).
 * The bot token is sourced from the existing config loader — typically
 * `process.env.DISCORD_BOT_TOKEN` — and is NEVER logged at any level.
 *
 * Posting itself is gated upstream through `ISupervisorAgent.evaluate(...)`.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { injectable } from 'tsyringe';
import { OutreachPublisherError, } from '../../../application/ports/output/services/outreach-publisher.interface.js';
const DISCORD_API_BASE = 'https://discord.com/api/v10';
const defaultTokenResolver = () => process.env.DISCORD_BOT_TOKEN ?? process.env.DISCORD_TOKEN;
const defaultFetch = (url, init) => fetch(url, init);
let DiscordOutreachPublisher = class DiscordOutreachPublisher {
    tokenResolver;
    httpFetch;
    constructor(tokenResolver = defaultTokenResolver, httpFetch = defaultFetch) {
        this.tokenResolver = tokenResolver;
        this.httpFetch = httpFetch;
    }
    async publishToDiscord(channelId, body) {
        const token = this.tokenResolver();
        if (!token || token.trim().length === 0) {
            throw new OutreachPublisherError('Discord bot token is not configured. Set DISCORD_BOT_TOKEN in the environment.');
        }
        const url = `${DISCORD_API_BASE}/channels/${channelId}/messages`;
        let response;
        try {
            response = await this.httpFetch(url, {
                method: 'POST',
                headers: {
                    Authorization: `Bot ${token}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ content: body }),
            });
        }
        catch (err) {
            throw new OutreachPublisherError(`Discord transport failed for channel ${channelId}`, err instanceof Error ? err : new Error(String(err)));
        }
        if (!response.ok) {
            const text = await safeText(response);
            throw new OutreachPublisherError(`Discord rejected message to ${channelId} (HTTP ${response.status}): ${redact(text, token)}`);
        }
        const json = (await response.json());
        return {
            messageId: json.id,
            postedAt: json.timestamp,
        };
    }
};
DiscordOutreachPublisher = __decorate([
    injectable(),
    __metadata("design:paramtypes", [Function, Function])
], DiscordOutreachPublisher);
export { DiscordOutreachPublisher };
async function safeText(response) {
    try {
        return await response.text();
    }
    catch {
        return '';
    }
}
function redact(text, token) {
    if (!text)
        return '';
    return text.split(token).join('[REDACTED]');
}
