import 'server-only';
import { prisma } from '../db/client';

export interface JobOutcome {
  itemsSeen: number;
  itemsOk: number;
  itemsFailed: number;
  detail?: Record<string, unknown>;
}

/**
 * Wraps a cron handler with a JobRun row so there's a queryable audit
 * trail (via Prisma Studio or any SQL client) in place of a CMS activity
 * log. Every /api/cron/* route should go through this.
 */
export async function withJobRun(job: string, fn: () => Promise<JobOutcome>) {
  const run = await prisma.jobRun.create({ data: { job, status: 'running' } });
  try {
    const outcome = await fn();
    const status = outcome.itemsFailed === 0 ? 'success' : outcome.itemsOk > 0 ? 'partial' : 'failed';
    await prisma.jobRun.update({
      where: { id: run.id },
      data: {
        status,
        itemsSeen: outcome.itemsSeen,
        itemsOk: outcome.itemsOk,
        itemsFailed: outcome.itemsFailed,
        detail: outcome.detail ?? undefined,
        finishedAt: new Date(),
      },
    });
    return outcome;
  } catch (err) {
    await prisma.jobRun.update({
      where: { id: run.id },
      data: {
        status: 'failed',
        detail: { error: err instanceof Error ? err.message : String(err) },
        finishedAt: new Date(),
      },
    });
    throw err;
  }
}
