/**
 * Issue Notifier — Discord webhook dispatch for the Trinity Console Issue Tracker.
 *
 * Posts to #issue-tracker via DISCORD_ISSUE_WEBHOOK_URL env var.
 * Failures are logged but never thrown — issue CRUD must never fail because
 * Discord is unreachable.
 *
 * Task #166 — REQ-2026-04-14-issue-tracker
 */

const axios = require('axios');

const WEBHOOK_URL = process.env.DISCORD_ISSUE_WEBHOOK_URL || '';

async function postWebhook(content) {
  if (!WEBHOOK_URL) {
    console.warn('[IssueNotifier] DISCORD_ISSUE_WEBHOOK_URL not set — skipping notify');
    return;
  }
  try {
    await axios.post(WEBHOOK_URL, { content }, { timeout: 5000 });
  } catch (err) {
    console.error('[IssueNotifier] webhook post failed:', err.message);
  }
}

function notifyCreated(issue) {
  const pri = String(issue.priority || 'medium').toUpperCase();
  return postWebhook(
    `🐛 Issue #${issue.issue_number} opened by **${issue.submitted_by}**: ` +
    `${issue.title} _(priority: ${pri}, category: ${issue.category})_`
  );
}

function notifyStatusChange(issue, newStatus, actor) {
  const icon = {
    open: '📂',
    in_progress: '🔧',
    blocked: '⛔',
    resolved: '✅',
    closed: '📦'
  }[newStatus] || '🔄';
  return postWebhook(
    `${icon} Issue #${issue.issue_number} → **${newStatus}** by ${actor || 'Trinity Console'}: ${issue.title}`
  );
}

function notifyComment(issue, author) {
  return postWebhook(
    `💬 New comment on Issue #${issue.issue_number} by **${author}**: ${issue.title}`
  );
}

module.exports = { notifyCreated, notifyStatusChange, notifyComment };
