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 combined todo counts (overdue + completed by me) for sidebar badges
router.get('/counts', todoController.getTodoCounts);

// Get overdue todos count
router.get('/overdue-count', todoController.getOverdueCount);

// Get completed todos created by current user
router.get('/completed-by-me', todoController.getCompletedByMeCount);

// Mark completed todos as notified (when user opens Todos page)
router.post('/mark-completed-notified', todoController.markCompletedAsNotified);

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

// Create new todo (any authenticated user)
router.post(
  '/',
  validateBody(createTodoSchema),
  todoController.createTodo
);

// Update todo (user must have access to the todo)
router.patch(
  '/:todoId',
  validateParams(z.object({ todoId: z.string().uuid() })),
  checkTodoAccess,
  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;
