/**
 * Image Controller
 * Handles image upload and management
 */

import { Request, Response } from 'express';
import { ImageService } from '../services/image.service';
import { triggerOCRProcessing } from '../services/ocr-processor.service';

export class ImageController {
  /**
   * Upload image (creates record)
   * POST /api/images
   */
  static async upload(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;

      // Handle multer file upload
      const file = req.file;
      const { document_id } = req.body;

      console.log('[UPLOAD] File received:', {
        originalname: file?.originalname,
        filename: file?.filename,
        path: file?.path,
        size: file?.size,
        mimetype: file?.mimetype,
        document_id,
      });

      if (!file) {
        res.status(400).json({
          success: false,
          error: '请选择要上传的文件',
        });
        return;
      }

      // 处理 document_id：空字符串转换为 null
      const processedDocumentId = document_id && document_id.trim() !== '' ? document_id : null;

      const image = await ImageService.create({
        user_id: userId,
        file_path: `/uploads/${file.filename}`,
        file_size: file.size,
        mime_type: file.mimetype,
        document_id: processedDocumentId,
      });

      // 触发异步 OCR 处理（不等待完成）
      triggerOCRProcessing(image.id, userId);

      res.status(201).json({
        success: true,
        data: image,
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : '上传图片失败';
      res.status(400).json({
        success: false,
        error: message,
      });
    }
  }

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

      if (!image) {
        res.status(404).json({
          success: false,
          error: '图片不存在',
        });
        return;
      }

      res.status(200).json({
        success: true,
        data: image,
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        error: '获取图片失败',
      });
    }
  }

  /**
   * Update OCR result
   * PUT /api/images/:id/ocr
   */
  static async updateOCR(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const { id } = req.params as { id: string };
      const { text, confidence } = req.body;

      const image = await ImageService.updateOCRResult(id, userId, text, confidence);

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

  /**
   * Link image to document
   * PUT /api/images/:id/link
   */
  static async linkToDocument(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const { id } = req.params as { id: string };
      const { document_id } = req.body;

      const image = await ImageService.linkToDocument(id, userId, document_id);

      res.status(200).json({
        success: true,
        data: image,
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : '关联文档失败';
      res.status(message.includes('not found') ? 404 : 400).json({
        success: false,
        error: message,
      });
    }
  }

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

      res.status(200).json({
        success: true,
        data: images,
        count: images.length,
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        error: '获取待处理图片失败',
      });
    }
  }

  /**
   * Get user images
   * GET /api/images
   */
  static async getUserImages(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const { document_id } = req.query;

      const images = await ImageService.findByUser(
        userId,
        document_id as string | undefined
      );

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

  /**
   * Convert image to todo
   * POST /api/images/:id/convert-to-todo
   */
  static async convertToTodo(req: Request, res: Response): Promise<void> {
    try {
      const userId = req.user!.user_id;
      const { id } = req.params as { id: string };
      const { title, description, priority } = req.body;

      // 获取图片信息
      const image = await ImageService.findById(id, userId);
      if (!image) {
        res.status(404).json({
          success: false,
          error: '图片不存在',
        });
        return;
      }

      // 检查是否有 OCR 结果
      if (!image.ocr_result || image.processing_status !== 'completed') {
        res.status(400).json({
          success: false,
          error: '图片尚未完成 OCR 识别，无法转换为待办',
        });
        return;
      }

      // 动态导入服务避免循环依赖
      const { TodoService } = await import('../services/todo.service');
      const { DocumentService } = await import('../services/document.service');

      // 如果图片还没有关联文档，先创建文档
      let documentId = image.document_id;
      if (!documentId) {
        const doc = await DocumentService.create({
          user_id: userId,
          title: title || `从图片提取: ${image.file_path.split('/').pop()}`,
          content: image.ocr_result,
        });
        documentId = doc.id;

        // 将图片关联到文档
        await ImageService.linkToDocument(id, userId, documentId);
      }

      // 从文档创建待办事项
      const todo = await TodoService.create({
        user_id: userId,
        title: title || `待办: ${image.ocr_result.slice(0, 50)}${image.ocr_result.length > 50 ? '...' : ''}`,
        description: description || image.ocr_result,
        priority: priority || 'medium',
        document_id: documentId,
      });

      res.status(201).json({
        success: true,
        data: todo,
        message: '已将 OCR 结果转换为待办事项',
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : '转换失败';
      res.status(400).json({
        success: false,
        error: message,
      });
    }
  }

  /**
   * Delete image
   * DELETE /api/images/: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 ImageService.delete(id, userId);

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