import mongoose, { Schema, Document } from 'mongoose';

export const CRON_RUN_STATUSES = ['SUCCESS', 'PARTIAL', 'FAILED'] as const;
export type CronRunStatus = (typeof CRON_RUN_STATUSES)[number];

// One document per scheduled execution of a cron job. A missing document for
// an expected run means the job never fired (e.g. server was down at the time).
export interface ICronRun extends Document {
  job_name: string;
  status: CronRunStatus;
  started_at: Date;
  finished_at: Date;
  duration_ms: number;
  result?: Record<string, unknown>;
  error?: string;
}

const cronRunSchema = new Schema<ICronRun>({
  job_name: { type: String, required: true, trim: true },
  status: { type: String, enum: CRON_RUN_STATUSES, required: true },
  started_at: { type: Date, required: true },
  finished_at: { type: Date, required: true },
  duration_ms: { type: Number, required: true, min: 0 },
  result: { type: Schema.Types.Mixed },
  error: { type: String },
});

cronRunSchema.index({ job_name: 1, started_at: -1 });

export default mongoose.model<ICronRun>('CronRun', cronRunSchema);
