import { FastifyInstance } from 'fastify';
import { authenticate } from '../hooks/authenticate';
import * as taskService from '../services/task.service';

export default async function taskRoutes(fastify: FastifyInstance) {
  fastify.get('/', async (request) => {
    const { page = '1', limit = '20' } = request.query as any;
    const [data, total] = await taskService.listTasks(parseInt(page), parseInt(limit));
    return { data, total, page: parseInt(page) };
  });

  fastify.post('/', { preHandler: authenticate }, async (request) => {
    const { title, userId } = request.body as any;
    return taskService.createTask(title, userId);
  });

  fastify.patch('/:id', { preHandler: authenticate }, async (request) => {
    const { id } = request.params as any;
    const { isCompleted } = request.body as any;
    return taskService.updateTask(parseInt(id), isCompleted);
  });
}
