import { prisma } from "./prisma";

// Pengaturan aplikasi (key-value). Saat ini dipakai untuk retensi pesan:
// pesan lebih lama dari periode ini dihapus otomatis agar database ringan.

export const MESSAGE_RETENTION_KEY = "message_retention";

export const RETENTION_PERIODS = {
  daily: { days: 1, label: "Harian (1 hari)" },
  weekly: { days: 7, label: "Mingguan (7 hari)" },
  monthly: { days: 30, label: "Bulanan (30 hari)" },
  yearly: { days: 365, label: "Tahunan (365 hari)" },
} as const;
export type RetentionPeriod = keyof typeof RETENTION_PERIODS;
const DEFAULT_RETENTION: RetentionPeriod = "monthly";

export async function getMessageRetention(): Promise<RetentionPeriod> {
  const row = await prisma.appSetting.findUnique({ where: { key: MESSAGE_RETENTION_KEY } });
  return row && row.value in RETENTION_PERIODS ? (row.value as RetentionPeriod) : DEFAULT_RETENTION;
}

export async function setMessageRetention(period: RetentionPeriod) {
  await prisma.appSetting.upsert({
    where: { key: MESSAGE_RETENTION_KEY },
    update: { value: period },
    create: { key: MESSAGE_RETENTION_KEY, value: period },
  });
}

// Hapus pesan yang melewati periode retensi. Dipanggil dari endpoint pesan,
// tapi di-throttle (per proses server) supaya polling 5 detik dari banyak
// client tidak memicu DELETE terus-menerus.
let lastCleanupAt = 0;
const CLEANUP_INTERVAL_MS = 10 * 60 * 1000; // paling sering tiap 10 menit

export async function cleanupOldMessages(force = false): Promise<number> {
  if (!force && Date.now() - lastCleanupAt < CLEANUP_INTERVAL_MS) return 0;
  lastCleanupAt = Date.now();
  const period = await getMessageRetention();
  const cutoff = new Date(Date.now() - RETENTION_PERIODS[period].days * 24 * 60 * 60 * 1000);
  const res = await prisma.message.deleteMany({ where: { createdAt: { lt: cutoff } } });
  return res.count;
}
