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

interface ConfigRow {
  valor: string;
}

export async function POST(req: NextRequest) {
  const data = await req.json();
  const { rg, nome, telefone, foto, fotosExtra, oficial, oficialDiscord, auxiliares, rgAdvogado, advogadoNome, artigos, atenuantes, itens, multa, fianca, pena, temFianca } = data;

  if (!artigos || artigos.length === 0) {
    return NextResponse.json({ ok: false, erro: "Selecione ao menos um artigo." });
  }

  const bicId = uuidv4();

  // Save/update prisoner
  if (rg && nome) {
    await query(
      "INSERT INTO presos (rg, nome, foto) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE nome = VALUES(nome), foto = IF(VALUES(foto) != '', VALUES(foto), foto)",
      [rg, nome, foto || null]
    );
  }

  // Save to history
  const artigosStr = artigos.join(", ");
  await query(
    "INSERT INTO historico_prisoes (rg_preso, resumo, artigos, multa_total, pena_total, oficial) VALUES (?, ?, ?, ?, ?, ?)",
    [rg, `BIC ${bicId}`, artigosStr, multa || 0, pena || 0, oficial || ""]
  );

  // Count arrests
  const countRows = (await query("SELECT COUNT(*) as total FROM historico_prisoes WHERE rg_preso = ?", [rg])) as { total: number }[];
  const totalPrisoes = countRows[0]?.total || 0;

  // Get webhook
  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. Acesse o admin PHP." });
  }

  // Build embed
  const dataHora = new Date().toLocaleString("pt-BR", { timeZone: "America/Sao_Paulo" });
  const dataAtual = new Date().toLocaleDateString("pt-BR", { timeZone: "America/Sao_Paulo" });

  const fields: { name: string; value: string; inline: boolean }[] = [];
  fields.push({ name: "👮 Policial Responsável", value: oficialDiscord || oficial || "-", inline: true });
  fields.push({ name: "📅 Data do Registro", value: dataHora, inline: true });
  if (auxiliares) fields.push({ name: "👥 Auxiliares", value: auxiliares, inline: false });

  let dadosConduzido = `**Nome:** ${nome}\n**RG:** ${rg}`;
  if (telefone) dadosConduzido += `\n**Telefone:** ${telefone}`;
  fields.push({ name: "📌 DADOS DO CONDUZIDO:", value: dadosConduzido, inline: false });

  const infracoes = artigos.map((a: string) => `• ${a};`).join("\n");
  fields.push({ name: "⚖️ INFRAÇÕES REGISTRADAS:", value: infracoes, inline: false });

  fields.push({ name: "📍 Total de Serviços Comunitários:", value: `**${pena || 0}**`, inline: true });
  fields.push({ name: "💰 Total de Multa:", value: `**R$ ${Number(multa || 0).toLocaleString("pt-BR")}**`, inline: true });

  if (temFianca && fianca > 0) {
    fields.push({ name: "🔓 Fiança:", value: `**R$ ${Number(fianca).toLocaleString("pt-BR")}**`, inline: true });
  }

  if (rgAdvogado || advogadoNome) {
    const advLabel = advogadoNome && rgAdvogado ? `${advogadoNome} (RG: ${rgAdvogado})` : advogadoNome || `RG: ${rgAdvogado}`;
    fields.push({ name: "🧑‍⚖️ Advogado:", value: advLabel, inline: true });
  }

  if (atenuantes && atenuantes.length > 0) {
    fields.push({ name: "⚖️ ATENUANTES:", value: atenuantes.map((a: string) => `• ${a}`).join("\n"), inline: false });
  }

  fields.push({ name: "📦 ITENS APREENDIDOS:", value: itens || "Nenhum item apreendido.", inline: false });

  if (totalPrisoes > 1) {
    fields.push({ name: "🔴 REINCIDÊNCIA", value: `Este cidadão já foi preso **${totalPrisoes}x**`, inline: false });
  }

  fields.push({ name: "🆔 ID Único do Documento:", value: `\`${bicId}\``, inline: false });

  let cor = 0x3498db;
  if (pena >= 60) cor = 0xe74c3c;
  else if (pena >= 30) cor = 0xe67e22;
  else if (pena >= 10) cor = 0xf1c40f;

  const embed: Record<string, unknown> = {
    title: "BOLETIM DE IDENTIFICAÇÃO CRIMINAL (BIC)",
    color: cor,
    fields,
    footer: { text: "Calculadora Penal — Capital RJ | Pulse Community" },
    timestamp: new Date().toISOString(),
  };

  const PUBLIC_BASE = "http://138.197.29.54";
  const fixUrl = (path: string) => {
    if (!path) return "";
    // Extrair filename e usar a API route para servir
    const filename = path.split("/").pop();
    return `${PUBLIC_BASE}/calculadora/api/uploads/${filename}`;
  };

  // Foto do rosto no rodapé do embed principal
  if (foto) {
    embed.image = { url: fixUrl(foto) };
  }

  const contentMsg = `**NOVO DOCUMENTO GERADO NO BANCO DE DADOS**\n👮 **POLICIAL RESPONSÁVEL:** ${oficialDiscord || oficial}\n-------------------------------------`;

  const payloadData: Record<string, unknown> = {
    content: contentMsg,
    embeds: [embed],
    username: "Calculadora Penal — Capital RJ",
  };

  const threadName = `BIC - ${nome} - RG: ${rg} - ${dataAtual}`;

  // 1) Enviar BIC principal
  let res = await fetch(webhook + "?wait=true", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payloadData),
  });

  // Se for canal de fórum, tentar com thread_name
  let isForum = false;
  if (res.status === 400) {
    const errData = await res.json().catch(() => null);
    if (errData?.code === 220001) {
      isForum = true;
      payloadData.thread_name = threadName;
      res = await fetch(webhook + "?wait=true", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payloadData),
      });
    }
  }

  if (!res.ok) {
    const errBody = await res.text().catch(() => "");
    return NextResponse.json({ ok: false, erro: `Erro HTTP ${res.status}. Verifique o webhook.`, debug: errBody });
  }

  const msgData = await res.json().catch(() => null);
  const messageId = msgData?.id || null;
  const channelId = msgData?.channel_id || null;

  // 2) Enviar fotos extras como segunda mensagem na mesma thread
  if (fotosExtra && Array.isArray(fotosExtra) && fotosExtra.length > 0) {
    const fotosEmbeds = fotosExtra.map((fp: string) => ({
      image: { url: fixUrl(fp) },
      color: cor,
    }));

    const fotosPayload: Record<string, unknown> = {
      content: `📸 **Fotos da prisão — ${nome} (RG: ${rg})**`,
      embeds: fotosEmbeds.slice(0, 10),
      username: "Calculadora Penal — Capital RJ",
    };

    // Se é fórum, enviar na mesma thread usando thread_id
    let fotosUrl = webhook + "?wait=true";
    if (isForum && channelId) {
      fotosUrl = webhook + `?wait=true&thread_id=${channelId}`;
    }

    await fetch(fotosUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(fotosPayload),
    });
  }

  // Salvar message_id no histórico
  if (messageId) {
    await query(
      "UPDATE historico_prisoes SET resumo = ? WHERE rg_preso = ? ORDER BY created_at DESC LIMIT 1",
      [`BIC ${bicId} | msg:${messageId} | ch:${channelId}`, rg]
    );
  }

  return NextResponse.json({ ok: true, total_prisoes: totalPrisoes, bic_id: bicId, message_id: messageId });
}
