import type { FastifyInstance } from "fastify";
import { z } from "zod";
import * as settings from "../../repos/settings.js";
import { loadTelegramConfig } from "../../telegram/bridge.js";
import { TelegramBot } from "../../telegram/bot.js";
import { writeAudit } from "../../audit/audit.js";

/**
 * Configurações da ponte Telegram. Config sensível (token) -> admin.
 * O token nunca é devolvido — só um indicador de presença.
 */
export async function settingsRoutes(app: FastifyInstance): Promise<void> {
  const adminOnly = { preHandler: app.requireRole("admin") };

  app.get("/settings/telegram", adminOnly, async () => {
    const enabled = (await settings.getText(settings.TELEGRAM_ENABLED)) === "1";
    const chatId = await settings.getText(settings.TELEGRAM_CHAT_ID);
    const hasToken = await settings.hasSecret(settings.TELEGRAM_BOT_TOKEN);
    return { enabled, chatId, hasToken };
  });

  app.put("/settings/telegram", adminOnly, async (req, reply) => {
    const body = z
      .object({
        enabled: z.boolean().optional(),
        token: z.string().min(1).nullish(), // ausente = mantém; null/"" não suportado p/ limpar aqui
        chatId: z.string().nullish(),
      })
      .safeParse(req.body);
    if (!body.success) return reply.code(400).send({ error: "Dados inválidos." });

    const d = body.data;
    if (d.enabled !== undefined) await settings.setText(settings.TELEGRAM_ENABLED, d.enabled ? "1" : "0");
    if (d.chatId !== undefined) await settings.setText(settings.TELEGRAM_CHAT_ID, d.chatId ?? null);
    if (d.token) await settings.setSecret(settings.TELEGRAM_BOT_TOKEN, d.token);

    await writeAudit({
      userId: req.user.sub,
      action: "settings.telegram",
      entity: "settings",
      detail: { enabled: d.enabled, chatId: d.chatId, tokenSet: !!d.token },
    });
    return { ok: true };
  });

  // Envia uma mensagem de teste ao grupo configurado.
  app.post("/settings/telegram/test", adminOnly, async (_req, reply) => {
    const cfg = await loadTelegramConfig();
    if (!cfg.token || !cfg.chatId) {
      return reply.code(400).send({ error: "Configure token e chatId primeiro." });
    }
    try {
      const bot = new TelegramBot(cfg.token);
      await bot.sendMessage(cfg.chatId, "✅ Teste do Painel P2P: a ponte do Telegram está funcionando.");
      return { ok: true };
    } catch (err) {
      return reply.code(502).send({ ok: false, error: err instanceof Error ? err.message : String(err) });
    }
  });
}
