import type { FastifyInstance } from 'fastify';

import { CreateTaskSchema, UpdateTaskSchema } from './types.js';
import * as repo from './repository.js';
import { BadRequestError } from '../../lib/errors.js';
import { DEFAULT_PRODUCT_ID } from '../../lib/product-config.js';

export async function taskRoutes(app: FastifyInstance) {
  /**
   * GET /tasks — List all extraction tasks.
   */
  app.get('/tasks', async (req, reply) => {
    const productId = (req.query as Record<string, string>).productId || DEFAULT_PRODUCT_ID;
    const tasks = await repo.listTasks(productId);
    return reply.send(tasks);
  });

  /**
   * GET /tasks/:id — Get a single task by ID.
   */
  app.get('/tasks/:id', async (req, reply) => {
    const { id } = req.params as { id: string };
    const productId = (req.query as Record<string, string>).productId || DEFAULT_PRODUCT_ID;
    const task = await repo.getTask(id, productId);
    return reply.send(task);
  });

  /**
   * POST /tasks — Create a custom task (admin only).
   */
  app.post('/tasks', async (req, reply) => {
    const parsed = CreateTaskSchema.safeParse(req.body);
    if (!parsed.success) {
      throw new BadRequestError(parsed.error.issues.map(i => i.message).join('; '));
    }

    const productId = parsed.data.productId || DEFAULT_PRODUCT_ID;
    const task = await repo.createTask(parsed.data, productId);
    return reply.status(201).send(task);
  });

  /**
   * PUT /tasks/:id — Update an existing task (admin only).
   */
  app.put('/tasks/:id', async (req, reply) => {
    const { id } = req.params as { id: string };
    const productId = (req.query as Record<string, string>).productId || DEFAULT_PRODUCT_ID;

    const parsed = UpdateTaskSchema.safeParse(req.body);
    if (!parsed.success) {
      throw new BadRequestError(parsed.error.issues.map(i => i.message).join('; '));
    }

    const task = await repo.updateTask(id, productId, parsed.data);
    return reply.send(task);
  });

  /**
   * DELETE /tasks/:id — Delete a custom task (admin only).
   */
  app.delete('/tasks/:id', async (req, reply) => {
    const { id } = req.params as { id: string };
    const productId = (req.query as Record<string, string>).productId || DEFAULT_PRODUCT_ID;
    await repo.deleteTask(id, productId);
    return reply.status(204).send();
  });
}
