import fetch from "node-fetch";

import { DiscordOutcome, EventInput } from "./types";

// Posts one notification mentioning a fixed role when a PR is opened.
// Everything about this is unconfirmed pending Kaius's spec for the
// Discord side of the integration (channel, message format, whether the
// role mention is even a raw role ID). Until DISCORD_WEBHOOK_URL and
// DISCORD_NOTIFY_ENABLED=true are both set, this just logs and no-ops.
export async function notifyDiscord(
  event: EventInput,
  pullRequestUrl: string | null
): Promise<DiscordOutcome> {
  const webhookUrl = process.env.DISCORD_WEBHOOK_URL;
  const roleId = process.env.DISCORD_ROLE_ID;
  const enabled = process.env.DISCORD_NOTIFY_ENABLED === "true";

  if (!enabled || !webhookUrl) {
    const reason = "Discord notification skipped (not configured for v1)";
    console.log(reason);
    return { notified: false, reason };
  }

  const mention = roleId ? `<@&${roleId}> ` : "";
  const content =
    `${mention}New event PR: **${event.name}**` +
    (pullRequestUrl ? ` — ${pullRequestUrl}` : " (PR not yet created)");

  const response = await fetch(webhookUrl, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ content }),
  });

  if (!response.ok) {
    const reason = `Discord webhook returned ${response.status}`;
    console.warn(reason);
    return { notified: false, reason };
  }

  return { notified: true, reason: "sent" };
}
