import type { FastifyInstance } from 'fastify';
import { createJob, getJob } from '../jobs/queue.js';
import { GenerateBodySchema } from '../types.js';

export async function generateRoutes(app: FastifyInstance): Promise<void> {
  app.post('/generate', async (request, reply) => {
    const parsed = GenerateBodySchema.safeParse(request.body);
    if (!parsed.success) {
      return reply.status(400).send({ error: 'invalid request', details: parsed.error.issues });
    }

    const { themeId } = parsed.data;
    const job = createJob(themeId);

    return reply.status(202).send({
      jobId: job.id,
      status: job.status,
      topicsFound: job.progress.topicsTotal,
      totalItems: job.progress.itemsTotal,
    });
  });

  app.get<{ Params: { jobId: string } }>('/status/:jobId', async (request, reply) => {
    const job = getJob(request.params.jobId);
    if (!job) {
      return reply.status(404).send({ error: 'job not found' });
    }

    return reply.send({
      jobId: job.id,
      status: job.status,
      progress: job.progress,
      error: job.error,
    });
  });
}
