import { FastifyInstance } from 'fastify';
import { runner } from '../jobs/importRunner';
import { importDirectory } from '../services/importService';

export default async function importRoutes(app: FastifyInstance) {
  app.post('/import/scan', async (request, reply) => {
    const body = request.body as any;

    // Encolar el job en background
    setImmediate(() => {
      runner
        .enqueue(async () => {
          // no await here; background task. Pasamos el logger de Fastify para
          // que los mensajes de advertencia se integren con el sistema de logs.
          return importDirectory({ dir: body?.dir, persist: body?.persist }, app.log);
        })
        .catch((err) => {
          app.log.warn({ err }, 'Background import task failed');
        });
    });

    // Responder inmediatamente
    reply.code(202).send({ status: 'queued' });
  });
}
