import { createClient } from "https://esm.sh/@supabase/supabase-js@2.45.4";

const BOT_TOKEN = Deno.env.get("TELEGRAM_BOT_TOKEN") || "8837960453:AAEzhn10FyuDYeo5QasuCOs8-UuZUG71Btc";
const WEBHOOK_SECRET = "telegramwebhook2024"; // must match the secret_token set on Telegram
const SUPABASE_URL = Deno.env.get("SUPABASE_URL")!;
const SUPABASE_SERVICE_ROLE_KEY = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;

Deno.serve(async (req) => {
  // Handle CORS preflight
  if (req.method === "OPTIONS") {
    return new Response("ok", {
      headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*" },
    });
  }

  try {
    // Verify the request is genuinely from Telegram using the secret token
    const incomingSecret = req.headers.get("x-telegram-bot-api-secret-token");
    if (incomingSecret !== WEBHOOK_SECRET) {
      console.error("Invalid secret token:", incomingSecret);
      return new Response(JSON.stringify({ error: "Forbidden" }), {
        status: 403,
        headers: { "Content-Type": "application/json" },
      });
    }

    const payload = await req.json();
    console.log("Telegram webhook payload:", JSON.stringify(payload));

    const message = payload.message;
    if (message && message.text) {
      const text = message.text.trim();
      const chatId = message.chat.id;

      // Handle "/start <volunteer_id>" or "/start <volunteer_id>_<random_token>"
      if (text.startsWith("/start")) {
        const parts = text.split(" ");
        if (parts.length > 1) {
          // Strip the random suffix we add to force Telegram to re-fire /start
          const rawPayload = parts[1];
          const volunteerId = rawPayload.includes("_")
            ? rawPayload.substring(0, rawPayload.lastIndexOf("_"))
            : rawPayload;

          console.log(`Linking chatId=${chatId} to volunteerId=${volunteerId}`);

          const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);

          const { data, error } = await supabase
            .from("profiles")
            .update({ telegram_chat_id: String(chatId) })
            .eq("id", volunteerId)
            .select("full_name")
            .single();

          if (error) {
            console.error("DB update error:", error.message);
            await sendTelegramMessage(chatId, `⚠️ Failed to link your account. Please try again.\n\nError: ${error.message}`);
          } else {
            console.log(`Linked chatId=${chatId} to ${data.full_name} (${volunteerId})`);
            await sendTelegramMessage(
              chatId,
              `✅ *Connected!*\n\nHello *${data.full_name}*, your Telegram has been linked to *Pusat Islam Smart Volunteer*.\n\nYou will now receive program reminders and announcements directly here! 🎉`
            );
          }
        } else {
          // /start with no payload — general welcome
          await sendTelegramMessage(
            chatId,
            `👋 Welcome to *Pusat Islam Reminders Bot*!\n\nTo connect your notifications, please go to your *Profile* page on the volunteer portal and click *Connect Telegram*.`
          );
        }
      }
    }

    return new Response(JSON.stringify({ ok: true }), {
      headers: { "Content-Type": "application/json" },
    });
  } catch (err: any) {
    console.error("Webhook handler error:", err);
    return new Response(JSON.stringify({ error: err.message }), {
      status: 500,
      headers: { "Content-Type": "application/json" },
    });
  }
});

async function sendTelegramMessage(chatId: number, text: string) {
  const res = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ chat_id: chatId, text, parse_mode: "Markdown" }),
  });
  if (!res.ok) {
    const err = await res.text();
    console.error("Error sending Telegram message:", err);
  }
}
