/**
 * 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,
      });

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

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

      // 触发异步 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: '获取图片列表失败',
      });
    }
  }

  /**
   * 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,
      });
    }
  }
}
