/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { execFile as execFileCb } from 'node:child_process';
import { promisify } from 'node:util';
import { readWorkspaceConfig } from './workspace-config.js';
const defaultExecFile = promisify(execFileCb);
function buildMessage(opts) {
    const kindLabel = opts.kind === 'transition' ? 'Phase transition gate' : 'Mid-phase gate';
    return (`[setup-agents] ${kindLabel} paused — story: ${opts.storyId}\n` +
        `Phase: ${opts.phase} | From: ${opts.fromRole} → To: ${opts.toRole}\n` +
        `Review ID: ${opts.reviewId}\n` +
        `Resume: ${opts.resumeCommand}`);
}
async function notifySlack(webhookEnvVar, message) {
    const url = process.env[webhookEnvVar];
    if (!url)
        return;
    const body = JSON.stringify({ text: message });
    const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body,
    });
    if (!response.ok) {
        throw new Error(`Slack notification failed: ${response.status} ${response.statusText}`);
    }
}
async function notifyGitHub(issueNumber, message, execFileFn) {
    await execFileFn('gh', ['issue', 'comment', issueNumber, '--body', message]);
}
export async function notifyGatePause(cwd, opts, deps = {}) {
    const config = readWorkspaceConfig(cwd);
    const notifications = config?.notifications;
    if (!notifications)
        return;
    const execFileFn = deps.execFile ?? defaultExecFile;
    const message = buildMessage(opts);
    const errors = [];
    await trySendSlack(notifications, message, errors);
    await trySendGitHub(notifications, opts.storyId, message, execFileFn, errors);
    if (errors.length > 0) {
        throw new AggregateError(errors, `Gate pause notification failed (${errors.length} error(s))`);
    }
}
async function trySendSlack(notifications, message, errors) {
    if (!notifications.slack)
        return;
    const envVar = notifications.slack.webhookEnvVar ?? 'SLACK_WEBHOOK_URL';
    try {
        await notifySlack(envVar, message);
    }
    catch (err) {
        errors.push(err instanceof Error ? err : new Error(String(err)));
    }
}
async function trySendGitHub(notifications, storyId, message, execFileFn, errors) {
    if (!notifications.github?.issueComment)
        return;
    if (!/^\d+$/.test(storyId))
        return;
    try {
        await notifyGitHub(storyId, message, execFileFn);
    }
    catch (err) {
        errors.push(err instanceof Error ? err : new Error(String(err)));
    }
}
//# sourceMappingURL=notifications.js.map