import { prisma } from "./prisma";
import { sendText } from "./evolution";

const COOLDOWN_MS = 5 * 60 * 1000; // anti-spam
const HYSTERESIS = 5; // % au-dessus du seuil pour ré-armer (évite les oscillations)

export const DEFAULT_BATTERY_MESSAGE =
  "🔋 Batterie faible : « {device} » est à {battery}% (seuil {threshold}%).";

export function formatBattery(
  template: string | null | undefined,
  data: { device: string; battery: number; threshold: number }
): string {
  return (template && template.trim() ? template : DEFAULT_BATTERY_MESSAGE)
    .replace(/\{device\}/g, data.device)
    .replace(/\{battery\}/g, String(data.battery))
    .replace(/\{threshold\}/g, String(data.threshold));
}

// Évalue l'alerte batterie pour une nouvelle valeur. Alerte au **passage** sous le seuil
// (une seule fois), se ré-arme quand la batterie remonte au-dessus de seuil + hystérésis.
// Best-effort : n'interrompt jamais l'ingestion.
export async function evaluateBatteryAlert(deviceId: string, battery: number): Promise<void> {
  try {
    const ba = await prisma.batteryAlert.findUnique({
      where: { deviceId },
      include: { device: true },
    });
    if (!ba || !ba.enabled) return;

    const below = battery <= ba.threshold;

    if (below) {
      if (ba.lastBelow === true) return; // déjà alerté, on attend une recharge
      const now = Date.now();
      const cool = ba.lastNotifiedAt ? now - ba.lastNotifiedAt.getTime() < COOLDOWN_MS : false;
      if (!cool) {
        const msg = formatBattery(ba.message, {
          device: ba.device.name,
          battery,
          threshold: ba.threshold,
        });
        try {
          await sendText(ba.notifyNumber, msg);
        } catch (e) {
          console.warn("[battery] envoi WhatsApp échoué:", (e as Error).message);
        }
      }
      await prisma.batteryAlert.update({
        where: { deviceId },
        data: { lastBelow: true, lastNotifiedAt: new Date() },
      });
    } else if (battery >= ba.threshold + HYSTERESIS && ba.lastBelow !== false) {
      // Ré-armement après recharge.
      await prisma.batteryAlert.update({ where: { deviceId }, data: { lastBelow: false } });
    }
  } catch (e) {
    console.warn("[battery] évaluation échouée:", (e as Error).message);
  }
}
