/**
 * Image Routes
 * Image API endpoints
 */

import { Router } from 'express';
import { ImageController } from '../controllers/image.controller';
import { authenticate } from '../middleware/auth.middleware';
import { upload } from '../middleware/upload.middleware';
import { triggerOCRProcessing, OCRProcessorService } from '../services/ocr-processor.service';
import { OCRProviderType } from '../services/ocr-providers';

const router = Router();

/**
 * @route   POST /api/images
 * @desc    Upload image
 * @access  Private
 */
router.post('/', authenticate, upload.single('file'), ImageController.upload);

/**
 * @route   GET /api/images
 * @desc    Get user images
 * @access  Private
 */
router.get('/', authenticate, ImageController.getUserImages);

/**
 * @route   GET /api/images/pending
 * @desc    Get pending images (OCR failed)
 * @access  Private
 */
router.get('/pending', authenticate, ImageController.getPending);

/**
 * @route   GET /api/images/ocr/providers
 * @desc    Get available OCR providers
 * @access  Private
 */
router.get('/ocr/providers', authenticate, async (_req, res) => {
  try {
    const providers = await OCRProcessorService.getAvailableProviders();
    res.json({
      success: true,
      data: providers,
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : '获取 OCR 提供商失败';
    res.status(500).json({
      success: false,
      error: message,
    });
  }
});

/**
 * @route   POST /api/images/ocr/test
 * @desc    Test OCR provider with uploaded image
 * @access  Private
 * @body    { provider: 'tesseract' | 'baidu' | 'rapidocr' | 'paddleocr' }
 */
router.post('/ocr/test', authenticate, upload.single('file'), async (req, res) => {
  try {
    const { provider } = req.body;

    if (!req.file) {
      res.status(400).json({
        success: false,
        error: '请上传测试图片',
      });
      return;
    }

    // 使用 OCRProcessorService 测试
    const result = await OCRProcessorService.testProvider(
      provider as OCRProviderType,
      req.file.path
    );

    res.json(result);
  } catch (error) {
    const message = error instanceof Error ? error.message : 'OCR 测试失败';
    res.status(500).json({
      success: false,
      error: message,
    });
  }
});

/**
 * @route   GET /api/images/:id
 * @desc    Get image by ID
 * @access  Private
 */
router.get('/:id', authenticate, ImageController.getById);

/**
 * @route   POST /api/images/:id/reprocess
 * @desc    Re-trigger OCR processing
 * @access  Private
 * @body    { provider?: 'tesseract' | 'baidu' | 'rapidocr' | 'auto' }
 */
router.post('/:id/reprocess', authenticate, async (req, res) => {
  try {
    const userId = typeof req.user!.user_id === 'string' ? req.user!.user_id : String(req.user!.user_id);
    const id = typeof req.params.id === 'string' ? req.params.id : req.params.id[0];
    const { provider } = req.body;

    // 触发 OCR 处理
    triggerOCRProcessing(id, userId, { provider: provider as OCRProviderType });

    res.json({
      success: true,
      message: 'OCR 处理已开始',
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : '重新处理失败';
    res.status(400).json({
      success: false,
      error: message,
    });
  }
});

/**
 * @route   PUT /api/images/:id/ocr
 * @desc    Update OCR result
 * @access  Private
 */
router.put('/:id/ocr', authenticate, ImageController.updateOCR);

/**
 * @route   PUT /api/images/:id/link
 * @desc    Link image to document
 * @access  Private
 */
router.put('/:id/link', authenticate, ImageController.linkToDocument);

/**
 * @route   POST /api/images/:id/convert-to-todo
 * @desc    Convert image OCR result to todo
 * @access  Private
 */
router.post('/:id/convert-to-todo', authenticate, ImageController.convertToTodo);

/**
 * @route   DELETE /api/images/:id
 * @desc    Delete image
 * @access  Private
 */
router.delete('/:id', authenticate, ImageController.delete);

export default router;
