import express from 'express';
import * as todoController from '../controllers/todo.controller.js';
import { authenticate } from '../middlewares/auth/authMiddleware.js';
import { requireAdmin } from '../middlewares/auth/roleMiddleware.js';
import { checkTodoAccess } from '../middlewares/auth/resourceAccessMiddleware.js';
import { validateBody, validateParams } from '../middlewares/security/validateInput.js';
import { createTodoSchema, updateTodoSchema } from '../validators/crm.validators.js';
import { z } from 'zod';

const router = express.Router();

// All todo routes require authentication
router.use(authenticate);

/**
 * Todo management
 */

// Get all todos
router.get('/', todoController.getAllTodos);

// Get todo by ID
router.get(
  '/:todoId',
  validateParams(z.object({ todoId: z.string().uuid() })),
  checkTodoAccess,
  todoController.getTodoById
);

// Create new todo (admin only)
router.post(
  '/',
  requireAdmin,
  validateBody(createTodoSchema),
  todoController.createTodo
);

// Update todo (admin only)
router.patch(
  '/:todoId',
  requireAdmin,
  validateParams(z.object({ todoId: z.string().uuid() })),
  validateBody(updateTodoSchema),
  todoController.updateTodo
);

// Delete todo (admin only)
router.delete(
  '/:todoId',
  requireAdmin,
  validateParams(z.object({ todoId: z.string().uuid() })),
  todoController.deleteTodo
);

// Toggle todo completion status
router.patch(
  '/:todoId/toggle',
  validateParams(z.object({ todoId: z.string().uuid() })),
  checkTodoAccess,
  todoController.toggleTodo
);

export default router;
