/**
 * Document Controller
 * Handles document API requests
 */

import { Request, Response } from 'express';
import { DocumentService } from '../services/document.service';

export class DocumentController {
  /**
   * Create a new document
   * POST /api/documents
   */
  static async create(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const { content, title, category_id } = req.body;

      const document = await DocumentService.create({
        user_id: userId,
        content,
        title,
        category_id,
      });

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

  /**
   * Get document by ID
   * GET /api/documents/: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 document = await DocumentService.findById(id, userId);

      if (!document) {
        res.status(404).json({
          success: false,
          error: '文档不存在',
        });
        return;
      }

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

  /**
   * Update document
   * PUT /api/documents/: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 { content, title, category_id } = req.body;

      const document = await DocumentService.update(id, userId, {
        content,
        title,
        category_id,
      });

      res.status(200).json({
        success: true,
        data: document,
      });
    } 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 document
   * DELETE /api/documents/: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 DocumentService.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 documents
   * GET /api/documents
   */
  static async getUserDocuments(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const { category_id, page, limit, search } = req.query;

      let documents;

      if (search && typeof search === 'string') {
        documents = await DocumentService.search(userId, search);
      } else {
        documents = await DocumentService.findByUser(userId, {
          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: documents,
        count: documents.length,
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : '获取文档列表失败';
      res.status(500).json({
        success: false,
        error: message,
      });
    }
  }
}
