import { v4 as uuid } from 'uuid';

export type JobStatus = 'pending' | 'running' | 'success' | 'failed';

export interface Job {
  id: string;
  type: string;
  status: JobStatus;
  payload: any;
  result?: any;
  retryCount: number;
  merchantId?: string;
  createdAt: number;
  updatedAt: number;
}

const jobQueue: Job[] = [];

export const createJob = (type: string, payload: any, merchantId?: string): Job => {
  const job: Job = {
    id: uuid(),
    type,
    payload,
    status: 'pending',
    retryCount: 0,
    merchantId,
    createdAt: Date.now(),
    updatedAt: Date.now()
  };
  
  jobQueue.push(job);
  console.log(`[JobQueue] Created job: ${type}`, job.id);
  return job;
};

export const getNextJob = (): Job | undefined => {
  return jobQueue.find(j => j.status === 'pending');
};

export const updateJob = (id: string, data: Partial<Job>): Job | undefined => {
  const job = jobQueue.find(j => j.id === id);
  if (job) {
    Object.assign(job, data);
    job.updatedAt = Date.now();
    console.log(`[JobQueue] Updated job: ${id}`, job.status);
  }
  return job;
};

export const getJobs = (): Job[] => {
  return jobQueue;
};

export const getJobsByMerchant = (merchantId: string): Job[] => {
  return jobQueue.filter(j => j.merchantId === merchantId);
};

export default {
  createJob,
  getNextJob,
  updateJob,
  getJobs,
  getJobsByMerchant
};
