import * as todoService from '../services/todo.service.js';

/**
 * Get all todos
 * GET /api/todos?search=query&projectId=xxx&companyId=xxx&assignedTo=xxx&status=xxx
 * Members only see todos they are assigned to
 */
export const getAllTodos = async (req, res, next) => {
  try {
    const { search, projectId, companyId, assignedTo, status, completed, priority } = req.query;
    const userId = req.user?.id;
    const userRole = req.user?.role;

    // Handle both 'status' and 'completed' query params
    let statusFilter = status;
    if (completed !== undefined) {
      statusFilter = completed === 'true' ? 'completed' : 'pending';
    }

    const filters = {
      searchTerm: search,
      projectId,
      companyId,
      assignedTo,
      status: statusFilter,
      priority,
    };

    const todos = await todoService.getAllTodos(filters, userId, userRole);

    res.status(200).json({
      success: true,
      count: todos.length,
      data: todos,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get my todos (assigned to current user)
 * GET /api/todos/my?status=xxx
 */
export const getMyTodos = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { status } = req.query;

    const filters = {
      assignedTo: userId,
      status,
    };

    const todos = await todoService.getAllTodos(filters);

    res.status(200).json({
      success: true,
      count: todos.length,
      data: todos,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get todo by ID
 * GET /api/todos/:todoId
 */
export const getTodoById = async (req, res, next) => {
  try {
    const { todoId } = req.params;

    const todo = await todoService.getTodoById(todoId);

    res.status(200).json({
      success: true,
      data: todo,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get todo with relations (project, company, assigned user, notes)
 * GET /api/todos/:todoId/details
 */
export const getTodoWithRelations = async (req, res, next) => {
  try {
    const { todoId } = req.params;

    const todo = await todoService.getTodoWithRelations(todoId);

    res.status(200).json({
      success: true,
      data: todo,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Create new todo
 * POST /api/todos
 * Body: { title, description, projectId, companyId, assignedUserIds, status, priority, dueDate }
 */
export const createTodo = async (req, res, next) => {
  try {
    const userId = req.userId;
    const data = req.body;

    const todo = await todoService.createTodo(userId, data, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(201).json({
      success: true,
      data: todo,
      message: 'Todo bolo vytvorené',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Update todo
 * PATCH /api/todos/:todoId
 * Body: { title, description, projectId, companyId, assignedUserIds, status, priority, dueDate }
 */
export const updateTodo = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { todoId } = req.params;
    const data = req.body;

    const todo = await todoService.updateTodo(todoId, data, userId, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(200).json({
      success: true,
      data: todo,
      message: 'Todo bolo aktualizované',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Delete todo
 * DELETE /api/todos/:todoId
 */
export const deleteTodo = async (req, res, next) => {
  try {
    const { todoId } = req.params;
    const userId = req.userId;

    const result = await todoService.deleteTodo(todoId, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(200).json({
      success: true,
      message: result.message,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Toggle todo completion status
 * PATCH /api/todos/:todoId/toggle
 */
export const toggleTodo = async (req, res, next) => {
  try {
    const { todoId } = req.params;
    const userId = req.userId;

    // Get current todo
    const todo = await todoService.getTodoById(todoId);
    const wasCompleted = todo.status === 'completed';

    // Toggle completed status
    const updated = await todoService.updateTodo(todoId, {
      status: wasCompleted ? 'pending' : 'completed',
    }, null, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(200).json({
      success: true,
      data: updated,
      message: 'Todo status aktualizovaný',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get overdue todos count
 * GET /api/todos/overdue-count
 */
export const getOverdueCount = async (req, res, next) => {
  try {
    const userId = req.userId;
    const userRole = req.user?.role;

    const count = await todoService.getOverdueCount(userId, userRole);

    res.status(200).json({
      success: true,
      data: { overdueCount: count },
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get completed todos created by current user count
 * GET /api/todos/completed-by-me
 */
export const getCompletedByMeCount = async (req, res, next) => {
  try {
    const userId = req.userId;

    const count = await todoService.getCompletedByMeCount(userId);

    res.status(200).json({
      success: true,
      data: { completedByMeCount: count },
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get combined todo counts for sidebar badges
 * GET /api/todos/counts
 */
export const getTodoCounts = async (req, res, next) => {
  try {
    const userId = req.userId;
    const userRole = req.user?.role;

    const counts = await todoService.getTodoCounts(userId, userRole);

    res.status(200).json({
      success: true,
      data: counts,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Mark all completed todos created by the user as notified
 * POST /api/todos/mark-completed-notified
 */
export const markCompletedAsNotified = async (req, res, next) => {
  try {
    const userId = req.userId;

    await todoService.markCompletedAsNotified(userId);

    res.status(200).json({
      success: true,
      message: 'Completed todos marked as notified',
    });
  } catch (error) {
    next(error);
  }
};
