/**
 * Todo Controller
 * Handles todo API requests with three-state workflow
 */

import { Request, Response } from 'express';
import { TodoService } from '../services/todo.service';

export class TodoController {
  /**
   * Create a new todo
   * POST /api/todos
   */
  static async create(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const { title, description, priority, due_date, category_id, document_id } = req.body;

      const todo = await TodoService.create({
        user_id: userId,
        title,
        description,
        priority,
        due_date: due_date ? new Date(due_date) : undefined,
        category_id,
        document_id,
      });

      res.status(201).json({
        success: true,
        data: todo,
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : '创建待办失败';
      res.status(400).json({
        success: false,
        error: message,
      });
    }
  }

  /**
   * Get todo by ID
   * GET /api/todos/:id
   */
  static async getById(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const { id } = req.params as { id: string };

      const todo = await TodoService.findById(id, userId);

      if (!todo) {
        res.status(404).json({
          success: false,
          error: '待办不存在',
        });
        return;
      }

      res.status(200).json({
        success: true,
        data: todo,
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : '获取待办失败';
      res.status(500).json({
        success: false,
        error: message,
      });
    }
  }

  /**
   * Update todo
   * PUT /api/todos/:id
   */
  static async update(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const { id } = req.params as { id: string };
      const { title, description, priority, status, due_date, category_id } = req.body;

      const todo = await TodoService.update(id, userId, {
        title,
        description,
        priority,
        status,
        due_date: due_date ? new Date(due_date) : undefined,
        category_id,
      });

      res.status(200).json({
        success: true,
        data: todo,
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : '更新待办失败';
      res.status(error instanceof Error && message.includes('not found') ? 404 : 400).json({
        success: false,
        error: message,
      });
    }
  }

  /**
   * Delete todo
   * DELETE /api/todos/:id
   */
  static async delete(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const { id } = req.params as { id: string };

      await TodoService.delete(id, userId);

      res.status(200).json({
        success: true,
        message: '待办已删除',
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : '删除待办失败';
      res.status(error instanceof Error && message.includes('not found') ? 404 : 400).json({
        success: false,
        error: message,
      });
    }
  }

  /**
   * Get user todos
   * GET /api/todos
   */
  static async getUserTodos(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const { status, priority, category_id, page, limit } = req.query;

      const todos = await TodoService.findByUser(userId, {
        status: status as any,
        priority: priority as any,
        category_id: category_id as string | undefined,
        page: page ? parseInt(page as string) : undefined,
        limit: limit ? parseInt(limit as string) : undefined,
      });

      res.status(200).json({
        success: true,
        data: todos,
        count: todos.length,
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : '获取待办列表失败';
      res.status(500).json({
        success: false,
        error: message,
      });
    }
  }

  /**
   * Get pending todos
   * GET /api/todos/pending
   */
  static async getPending(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const todos = await TodoService.getPendingTodos(userId);

      res.status(200).json({
        success: true,
        data: todos,
        count: todos.length,
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        error: '获取待办列表失败',
      });
    }
  }

  /**
   * Get completed todos
   * GET /api/todos/completed
   */
  static async getCompleted(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const todos = await TodoService.getCompletedTodos(userId);

      res.status(200).json({
        success: true,
        data: todos,
        count: todos.length,
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        error: '获取已完成列表失败',
      });
    }
  }

  /**
   * Get confirmed todos
   * GET /api/todos/confirmed
   */
  static async getConfirmed(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const todos = await TodoService.getConfirmedTodos(userId);

      res.status(200).json({
        success: true,
        data: todos,
        count: todos.length,
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        error: '获取已确认列表失败',
      });
    }
  }
}
