import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";

interface ConfigRow { valor: string; }

export async function POST(req: NextRequest) {
  const { messageId } = await req.json();
  if (!messageId) return NextResponse.json({ ok: false, erro: "ID da mensagem não fornecido." });

  const configRows = (await query("SELECT valor FROM config WHERE chave = 'discord_webhook'")) as ConfigRow[];
  const webhook = configRows[0]?.valor?.trim() || "";
  if (!webhook) return NextResponse.json({ ok: false, erro: "Webhook não configurado." });

  // Extrair webhook ID e token da URL
  const match = webhook.match(/webhooks\/(\d+)\/([^/?]+)/);
  if (!match) return NextResponse.json({ ok: false, erro: "Webhook inválido." });

  const deleteUrl = `https://discord.com/api/webhooks/${match[1]}/${match[2]}/messages/${messageId}`;
  const res = await fetch(deleteUrl, { method: "DELETE" });

  if (res.ok || res.status === 204) {
    return NextResponse.json({ ok: true });
  }

  return NextResponse.json({ ok: false, erro: `Erro HTTP ${res.status}` });
}
