/**
 * Cron Logger — wraps cron handlers with timing + status persistence.
 * Records start, duration, success/error for the admin cron dashboard.
 */

import { prisma } from "@/lib/prisma";

export async function logCron<T>(route: string, fn: () => Promise<T>): Promise<T> {
  const start = Date.now();
  try {
    const result = await fn();
    await prisma.cronLog.create({
      data: {
        route,
        status: "success",
        duration: Date.now() - start,
        details: JSON.stringify(result).slice(0, 500),
      },
    }).catch(() => null);
    return result;
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    await prisma.cronLog.create({
      data: {
        route,
        status: "error",
        duration: Date.now() - start,
        details: msg.slice(0, 500),
      },
    }).catch(() => null);
    throw error;
  }
}
