export interface DiscordSaleNotification {
  planName: string;
  amountFormatted: string;
  currency: string;
  customerEmail?: string;
  sessionId?: string;
}

/**
 * Sends real-time Rich Embed notifications to Discord when a sale / upgrade occurs
 */
export async function sendDiscordSaleAlert(sale: DiscordSaleNotification): Promise<boolean> {
  const webhookUrl = process.env.DISCORD_SALES_WEBHOOK_URL;
  if (!webhookUrl) {
    console.log("No DISCORD_SALES_WEBHOOK_URL configured, skipping notification:", sale);
    return false;
  }

  try {
    const embed = {
      title: "💰 Neuer Verkauf / Pro-Aktivierung!",
      color: 0x10b981, // Emerald Green
      description: `Ein Nutzer hat soeben **Receipt Scanner Pro** gekauft!`,
      fields: [
        {
          name: "📦 Plan / Paket",
          value: `**${sale.planName}**`,
          inline: true,
        },
        {
          name: "💵 Betrag",
          value: `**${sale.amountFormatted}**`,
          inline: true,
        },
        {
          name: "👤 Kunde (Email)",
          value: sale.customerEmail || "Gast-Checkout",
          inline: false,
        },
        {
          name: "🕒 Zeitstempel",
          value: new Date().toLocaleString("de-DE", { timeZone: "Europe/Berlin" }),
          inline: false,
        },
      ],
      footer: {
        text: "ScanReceipts • Instant Sales Bot",
      },
    };

    const res = await fetch(webhookUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        username: "ScanReceipts Sales Bot",
        avatar_url: "https://scanreceipts.app/icon.png",
        embeds: [embed],
      }),
    });

    return res.ok;
  } catch (error) {
    console.error("Failed to send Discord alert:", error);
    return false;
  }
}
