import { createRouter } from '../../create-router';
import { enqueueJob, cancelJob, listAllJobs, readJob } from '../../queue/init';
import { NOT_FOUND } from '../../custom-errors';

export const queueRouter = createRouter();

queueRouter.get('/jobs', async (ctx) => {
  const user = ctx.get('user');
  const lane = ctx.req.query('lane');
  const type = ctx.req.query('type');
  const status = ctx.req.query('status');

  let jobs = await listAllJobs();
  jobs = jobs.filter((j) => j.userId === user.email);

  if (lane) jobs = jobs.filter((j) => j.lane === lane);
  if (type) jobs = jobs.filter((j) => j.type === type);
  if (status) jobs = jobs.filter((j) => j.status === status);

  return ctx.json(jobs);
});

queueRouter.get('/jobs/:id', async (ctx) => {
  const job = await readJob(ctx.req.param('id'));
  if (!job) throw NOT_FOUND('Job not found');
  return ctx.json(job);
});

queueRouter.post('/jobs', async (ctx) => {
  const user = ctx.get('user');
  const body = ctx.get('body');
  const { lane, type, meta, notify } = body as {
    lane: string;
    type: string;
    meta?: Record<string, unknown>;
    notify?: boolean;
  };

  const job = await enqueueJob({ lane, type, userId: user.email, meta, notify });
  return ctx.json(job, 201);
});

queueRouter.delete('/jobs/:id', async (ctx) => {
  const job = await cancelJob(ctx.req.param('id'));
  if (!job) throw NOT_FOUND('Job not found');
  return ctx.json(job);
});
