import { db } from "@/lib/db";
import { pagos, cuotasEsperadas, indicesIpc } from "@/lib/schema";
import { eq, and } from "drizzle-orm";
import { sendText } from "@/lib/bot/evolution";
import { calcularAjustesIpc, obtenerAlquilerEsperado } 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 ?? "";

export async function GET(req: Request) {
  // Protect endpoint
  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 periodoActual = `${hoy.getFullYear()}-${String(hoy.getMonth() + 1).padStart(2, "0")}`;

  // Check if alquiler for current period is paid
  const pagoRows = await db
    .select()
    .from(pagos)
    .where(and(eq(pagos.contratoId, 1), eq(pagos.periodo, periodoActual)));

  if (pagoRows.length > 0) {
    return Response.json({ sent: false, reason: "Alquiler ya registrado para este período" });
  }

  // Calculate expected amount
  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 montoIpc = obtenerAlquilerEsperado(periodoActual, ajustes, CONTRATO.montoBaseInicial);
  const montoAcordado = periodoActual >= "2026-03" ? 4_500_000 : null;

  // Calculate days overdue
  const diaVenc = CONTRATO.diaVencimiento;
  const [anio, mes] = periodoActual.split("-").map(Number);
  const fechaVenc = new Date(anio, mes - 1, diaVenc);
  const diasMora = Math.max(0, Math.floor((hoy.getTime() - fechaVenc.getTime()) / (1000 * 60 * 60 * 24)));
  const penalidad = diasMora > 0 ? Math.round(montoIpc * CONTRATO.penalDiario * Math.min(diasMora, 30)) : 0;

  const lines = [
    `⚠️ *Recordatorio de alquiler — ${periodoActual}*`,
    ``,
    `El alquiler de ${periodoActual} aún no ha sido cobrado.`,
    ``,
    `📋 Detalles:`,
    `  • Monto IPC: $${montoIpc.toLocaleString("es-AR")}`,
  ];

  if (montoAcordado) {
    lines.push(`  • Monto acordado: $${montoAcordado.toLocaleString("es-AR")}`);
  }

  if (diasMora > 0) {
    lines.push(`  • Días de mora: ${diasMora}`);
    lines.push(`  • Penalidad: $${penalidad.toLocaleString("es-AR")}`);
    lines.push(`  • Total con mora: $${(montoIpc + penalidad).toLocaleString("es-AR")}`);
  }

  lines.push(``, `_Myristica · Arcos 1836_`);

  if (GROUP_JID) {
    await sendText(GROUP_JID, lines.join("\n"));
    return Response.json({ sent: true, periodo: periodoActual, diasMora });
  }

  return Response.json({ sent: false, reason: "WHATSAPP_GROUP_JID no configurado", message: lines.join("\n") });
}
