import crypto from "node:crypto";
import express from "express";

import { getTelegramBot, telegramBotConfig } from "$root/bot/index.js";

const router = express.Router();

const secretsMatch = (left, right) => {
  const leftBuffer = Buffer.from(String(left || ""));
  const rightBuffer = Buffer.from(String(right || ""));

  return (
    leftBuffer.length === rightBuffer.length &&
    leftBuffer.length > 0 &&
    crypto.timingSafeEqual(leftBuffer, rightBuffer)
  );
};

router.get("/health", (_req, res) => {
  res.status(200).send({
    enabled: telegramBotConfig.enabled,
    mode: telegramBotConfig.mode,
    developmentMode: telegramBotConfig.developmentMode,
  });
});

router.post("/webhook", async (req, res) => {
  if (telegramBotConfig.mode !== "webhook") {
    return res.status(404).send({ message: "Not found" });
  }

  const receivedSecret = req.get("x-telegram-bot-api-secret-token");
  if (!secretsMatch(receivedSecret, telegramBotConfig.webhookSecret)) {
    return res.status(401).send({ message: "Unauthorized" });
  }

  try {
    await getTelegramBot().handleUpdate(req.body);
    return res.sendStatus(200);
  } catch (error) {
    console.error(
      "[telegram-bot] webhook update failed:",
      error?.message || "unknown error",
    );
    return res.sendStatus(500);
  }
});

export default router;
