import { BaseJob, JobType } from '@/types';
import { logger } from '@/lib/logger';

class QueueProducer {
  private jobs: BaseJob[] = [];

  async enqueue<T extends Record<string, unknown>>(
    type: JobType,
    shopId: string,
    payload: T,
    options: { priority?: number; maxAttempts?: number; delayMs?: number } = {}
  ): Promise<BaseJob<T>> {
    const now = new Date();
    const runAt = options.delayMs ? new Date(now.getTime() + options.delayMs).toISOString() : now.toISOString();

    const job: BaseJob<T> = {
      id: `job_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
      type,
      shop_id: shopId,
      payload,
      priority: options.priority || 1,
      attempts: 0,
      max_attempts: options.maxAttempts || 3,
      status: 'queued',
      created_at: now.toISOString(),
      updated_at: now.toISOString(),
      run_at: runAt,
    };

    this.jobs.push(job as BaseJob);
    logger.info(`Job enqueued: [${type}] for shop ${shopId} (Job ID: ${job.id})`);

    // In a serverless / microservice environment, workers can poll or be triggered automatically
    setTimeout(() => {
      import('./worker').then(({ queueWorker }) => {
        queueWorker.processJob(job.id);
      }).catch((err) => {
        logger.error('Failed to trigger worker process', err);
      });
    }, 10);

    return job;
  }

  getJob(id: string): BaseJob | undefined {
    return this.jobs.find((j) => j.id === id);
  }

  getAllJobs(shopId?: string): BaseJob[] {
    if (shopId) {
      return this.jobs.filter((j) => j.shop_id === shopId);
    }
    return this.jobs;
  }
}

export const queueProducer = new QueueProducer();
