import { supabaseExtAdmin } from "@/integrations/external-supabase/client.server";

export async function notifyNewOrder(orderId: string) {
  const { data: settings } = await supabaseExtAdmin
    .from("telegram_settings")
    .select("bot_token, admin_chat_id, is_enabled")
    .eq("id", 1)
    .maybeSingle();

  if (!settings?.is_enabled || !settings.bot_token || !settings.admin_chat_id) return;

  const { data: order } = await supabaseExtAdmin
    .from("orders")
    .select("*")
    .eq("id", orderId)
    .single();

  if (!order) return;

  const text = [
    `🔔 *New Order* \`#${String(order.order_number).padStart(4, "0")}\``,
    `📦 ${order.package_name} × ${order.quantity} = *${order.total_credits} Credits*`,
    `💰 ৳${order.total_bdt}`,
    `📧 ${order.customer_email}`,
    order.whatsapp ? `📱 ${order.whatsapp}` : null,
    `💳 ${order.payment_method.toUpperCase()}${order.transaction_id ? ` — TXN: \`${order.transaction_id}\`` : ""}`,
    order.notes ? `📝 ${order.notes}` : null,
  ].filter(Boolean).join("\n");

  const res = await fetch(`https://api.telegram.org/bot${settings.bot_token}/sendMessage`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      chat_id: settings.admin_chat_id,
      text,
      parse_mode: "Markdown",
      reply_markup: {
        inline_keyboard: [[
          { text: "✅ Verify", callback_data: `verify:${order.id}` },
          { text: "🚫 Reject", callback_data: `reject:${order.id}` },
        ], [
          { text: "📧 Mark Delivered", callback_data: `deliver:${order.id}` },
        ]],
      },
    }),
  });

  if (res.ok) {
    const data = await res.json();
    if (data?.result?.message_id) {
      await supabaseExtAdmin.from("orders").update({ telegram_message_id: data.result.message_id }).eq("id", order.id);
    }
  }
}