import { prisma as db } from "@repo/db/client";

export type CronJobStatus = "success" | "failed" | "skipped";

export interface CronJobLogEntry {
  id: number;
  jobName: string;
  status: string;
  startedAt: Date;
  completedAt: Date | null;
  durationMs: number | null;
  errorMessage: string | null;
}

export const cronJobLogStorage = {
  async createJobLog(
    jobName: string,
    startedAt: Date
  ): Promise<CronJobLogEntry> {
    return db.cronJobLog.create({
      data: { jobName, status: "running", startedAt },
    });
  },

  async completeJobLog(
    id: number,
    jobName: string,
    startedAt: Date,
    status: CronJobStatus,
    completedAt: Date,
    errorMessage?: string
  ): Promise<CronJobLogEntry> {
    const durationMs = completedAt.getTime() - startedAt.getTime();
    const existing = await db.cronJobLog.findUnique({ where: { id } });
    if (existing) {
      return db.cronJobLog.update({
        where: { id },
        data: { status, completedAt, durationMs, errorMessage: errorMessage ?? null },
      });
    }
    return db.cronJobLog.create({
      data: { jobName, status, startedAt, completedAt, durationMs, errorMessage: errorMessage ?? null },
    });
  },

  async getRecentLogs(limit = 50): Promise<CronJobLogEntry[]> {
    return db.cronJobLog.findMany({
      orderBy: { startedAt: "desc" },
      take: limit,
    });
  },

  async getLastRunPerJob(): Promise<CronJobLogEntry[]> {
    // Get the most recent log entry for each distinct jobName
    const jobs = await db.cronJobLog.findMany({
      distinct: ["jobName"],
      orderBy: { startedAt: "desc" },
    });
    return jobs;
  },

  async getFailedLogs(limit = 20): Promise<CronJobLogEntry[]> {
    return db.cronJobLog.findMany({
      where: { status: "failed" },
      orderBy: { startedAt: "desc" },
      take: limit,
    });
  },
};
