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

const documentRoutes: FastifyPluginAsync = async (app) => {
  app.post('/ingest', async (request, reply) => {
    const parsed = IngestBodySchema.safeParse(request.body);
    if (!parsed.success) {
      return reply.status(400).send({ error: 'Invalid request body', details: parsed.error.format() });
    }
    const job = createJob(parsed.data);
    return reply.status(202).send({ jobId: job.id, status: job.status });
  });

  app.get<{ Params: { jobId: string } }>('/ingest/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,
      chunksTotal: job.progress.chunksTotal,
      chunksEmbedded: job.progress.chunksEmbedded,
      themesFound: job.progress.themesFound,
      topicsFound: job.progress.topicsFound,
      reason: job.error ?? undefined,
    });
  });
};

export default documentRoutes;
