export type JobStatus = 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';

export type JobStepStatus = 'pending' | 'running' | 'completed' | 'failed';

export type JobProgress = {
  current: number;
  total: number;
  label?: string;
};

export type JobStep = {
  name: string;
  status: JobStepStatus;
  startedAt?: number;
  completedAt?: number;
  error?: string;
  progress?: JobProgress;
};

export type Job = {
  id: string;
  lane: string;
  type: string;
  userId: string;
  status: JobStatus;
  steps: JobStep[];
  currentStep: number;
  error?: string;
  createdAt: number;
  startedAt?: number;
  completedAt?: number;
  retryAt?: number;
  retries?: number;
  meta?: Record<string, unknown>;
  notify?: boolean;
};

export type StepContext = {
  job: Job;
  step: JobStep;
  updateProgress: (progress: JobProgress) => Promise<void>;
  meta: Record<string, unknown>;
};

export type JobHandlerStep = {
  name: string;
  run: (ctx: StepContext) => Promise<void>;
};

export type RetryConfig = {
  delayMs: number;
  maxRetries: number;
};

export type JobHandler = {
  type: string;
  steps: JobHandlerStep[];
  retry?: RetryConfig;
};

export type EnqueueParams = {
  lane: string;
  type: string;
  userId: string;
  meta?: Record<string, unknown>;
  notify?: boolean;
};

/** Throw this from a step to fail the job immediately without retrying. */
export class PermanentError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'PermanentError';
  }
}
