import * as todoService from '../services/todo.service.js';
import { formatErrorResponse } from '../utils/errors.js';

/**
 * Get all todos
 * GET /api/todos?search=query&projectId=xxx&companyId=xxx&assignedTo=xxx&status=xxx
 */
export const getAllTodos = async (req, res) => {
  try {
    const { search, projectId, companyId, assignedTo, status } = req.query;

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

    const todos = await todoService.getAllTodos(filters);

    res.status(200).json({
      success: true,
      count: todos.length,
      data: todos,
    });
  } catch (error) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};

/**
 * Get my todos (assigned to current user)
 * GET /api/todos/my?status=xxx
 */
export const getMyTodos = async (req, res) => {
  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) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};

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

    const todo = await todoService.getTodoById(todoId);

    res.status(200).json({
      success: true,
      data: todo,
    });
  } catch (error) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};

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

    const todo = await todoService.getTodoWithRelations(todoId);

    res.status(200).json({
      success: true,
      data: todo,
    });
  } catch (error) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};

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

    console.log('Backend received todo data:', data);
    const todo = await todoService.createTodo(userId, data);

    res.status(201).json({
      success: true,
      data: todo,
      message: 'Todo bolo vytvorené',
    });
  } catch (error) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};

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

    console.log('Backend received update data:', data);
    const todo = await todoService.updateTodo(todoId, data);

    res.status(200).json({
      success: true,
      data: todo,
      message: 'Todo bolo aktualizované',
    });
  } catch (error) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};

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

    const result = await todoService.deleteTodo(todoId);

    res.status(200).json({
      success: true,
      message: result.message,
    });
  } catch (error) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};

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

    // Get current todo
    const todo = await todoService.getTodoById(todoId);

    // Toggle completed status
    const updated = await todoService.updateTodo(todoId, {
      status: todo.status === 'completed' ? 'pending' : 'completed',
    });

    res.status(200).json({
      success: true,
      data: updated,
      message: 'Todo status aktualizovaný',
    });
  } catch (error) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};
