import { db } from "@/lib/db";
import { indicesIpc } from "@/lib/schema";
import { sendText } from "@/lib/bot/evolution";
import { calcularAjustesIpc } from "@/lib/ipc";
import { CONTRATO, CALENDARIO_AJUSTES, IPC_DATOS } from "@/lib/contract";

const GROUP_JID = process.env.WHATSAPP_GROUP_JID ?? "";
const CRON_SECRET = process.env.CRON_SECRET ?? process.env.BOT_WEBHOOK_SECRET ?? "";
const ALERT_DAYS_BEFORE = 7;

export async function GET(req: Request) {
  const auth = req.headers.get("authorization") ?? "";
  if (CRON_SECRET && auth !== `Bearer ${CRON_SECRET}`) {
    return Response.json({ error: "Forbidden" }, { status: 403 });
  }

  const hoy = new Date();
  const hoyStr = hoy.toISOString().slice(0, 7); // YYYY-MM

  // Find upcoming adjustments within ALERT_DAYS_BEFORE days
  const upcoming = [...CALENDARIO_AJUSTES].filter((c) => {
    const [y, m] = c.fechaAjuste.split("-").map(Number);
    const adjDate = new Date(y, m - 1, 1);
    const diffDays = Math.floor((adjDate.getTime() - hoy.getTime()) / (1000 * 60 * 60 * 24));
    return diffDays >= 0 && diffDays <= ALERT_DAYS_BEFORE;
  });

  if (upcoming.length === 0) {
    return Response.json({ sent: false, reason: "No hay ajustes próximos" });
  }

  const ipcRows = await db.select().from(indicesIpc).orderBy(indicesIpc.anio, indicesIpc.mes);
  const ipcData: Record<string, number> = { ...IPC_DATOS };
  for (const row of ipcRows) {
    const key = `${row.anio}-${String(row.mes).padStart(2, "0")}`;
    ipcData[key] = row.valor;
  }

  const ajustes = calcularAjustesIpc(ipcData, [...CALENDARIO_AJUSTES], CONTRATO.montoBaseInicial);
  const montoActual =
    ajustes.length > 0 ? ajustes[ajustes.length - 1].montoNuevo : CONTRATO.montoBaseInicial;

  const messages: string[] = [];

  for (const adj of upcoming) {
    const tieneIndices = ipcData[adj.mesIndiceInicio] && ipcData[adj.mesIndiceFin];
    const [y, m] = adj.fechaAjuste.split("-").map(Number);
    const adjDate = new Date(y, m - 1, 1);
    const diffDays = Math.floor((adjDate.getTime() - hoy.getTime()) / (1000 * 60 * 60 * 24));

    const lines = [
      `📈 *Ajuste IPC próximo — ${adj.fechaAjuste}*`,
      ``,
      diffDays === 0
        ? `🔔 El ajuste IPC entra en vigencia *hoy*.`
        : `🔔 El ajuste IPC entra en vigencia en *${diffDays} día${diffDays !== 1 ? "s" : ""}*.`,
      ``,
      `📋 Detalles del ajuste:`,
      `  • Período IPC: ${adj.mesIndiceInicio} → ${adj.mesIndiceFin}`,
      `  • Monto actual: $${montoActual.toLocaleString("es-AR")}`,
    ];

    if (tieneIndices) {
      const coef = ipcData[adj.mesIndiceFin] / ipcData[adj.mesIndiceInicio];
      const montoNuevo = Math.round(montoActual * coef);
      const variacion = ((coef - 1) * 100).toFixed(2);
      lines.push(`  • Variación IPC: +${variacion}%`);
      lines.push(`  • *Nuevo monto: $${montoNuevo.toLocaleString("es-AR")}*`);
    } else {
      lines.push(`  • (Índices INDEC pendientes de publicación)`);
    }

    lines.push(``, `_Contrato cláusula CUARTA — Arcos 1836_`);
    messages.push(lines.join("\n"));
  }

  if (GROUP_JID && messages.length > 0) {
    for (const msg of messages) {
      await sendText(GROUP_JID, msg);
    }
    return Response.json({ sent: true, adjustments: upcoming.map((a) => a.fechaAjuste) });
  }

  return Response.json({
    sent: false,
    reason: "WHATSAPP_GROUP_JID no configurado",
    messages,
  });
}
