import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { ErrorSchema } from '@/server/utils/errorHandler';
import { AppDataSource } from '@/server/data-source';
import { DocumentService } from '@/server/modules/documents/document.service';
import { AuthContext } from '@/server/types/context';
import { authMiddleware } from '@/server/middleware/auth.middleware';

// 请求Schema
const MergeRequestSchema = z.object({
  files: z.array(z.instanceof(File)).openapi({
    description: '要合并的Word文档文件',
    example: [] // 文件数组示例
  }),
  outputFormat: z.enum(['pdf', 'docx']).default('docx').openapi({
    description: '输出格式',
    example: 'docx'
  }),
  preserveFormatting: z.coerce.boolean().default(true).openapi({
    description: '是否保持原有格式',
    example: true
  })
});

// 响应Schema
const MergeResponseSchema = z.object({
  success: z.boolean().openapi({
    description: '是否成功',
    example: true
  }),
  message: z.string().openapi({
    description: '操作结果消息',
    example: '文档合并成功'
  }),
  fileName: z.string().openapi({
    description: '合并后的文件名',
    example: 'merged_document.docx'
  }),
  fileSize: z.number().openapi({
    description: '文件大小（字节）',
    example: 10240
  }),
  downloadUrl: z.string().openapi({
    description: '下载URL',
    example: '/api/v1/documents/download/merged_document.docx'
  })
});

// 路由定义
const routeDef = createRoute({
  method: 'post',
  path: '/merge',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'multipart/form-data': {
          schema: MergeRequestSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '文档合并成功',
      content: {
        'application/json': { schema: MergeResponseSchema }
      }
    },
    400: {
      description: '请求参数错误',
      content: {
        'application/json': { schema: ErrorSchema }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': { schema: ErrorSchema }
      }
    }
  }
});

// 路由实现
const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const formData = await c.req.formData();
    const files = formData.getAll('files') as File[];
    const outputFormat = formData.get('outputFormat') as string || 'docx';
    const preserveFormatting = formData.get('preserveFormatting') === 'true';

    if (!files || files.length < 2) {
      return c.json({ 
        code: 400, 
        message: '请至少选择2个Word文档进行合并' 
      }, 400);
    }

    // 验证文件类型
    for (const file of files) {
      const fileName = file.name.toLowerCase();
      if (!fileName.endsWith('.doc') && !fileName.endsWith('.docx')) {
        return c.json({ 
          code: 400, 
          message: `文件 ${file.name} 不是Word文档格式` 
        }, 400);
      }
    }

    const documentService = new DocumentService(AppDataSource);
    
    // 读取所有文件内容
    const fileBuffers: Buffer[] = [];
    for (const file of files) {
      const arrayBuffer = await file.arrayBuffer();
      fileBuffers.push(Buffer.from(arrayBuffer));
    }

    // 执行文档合并流程
    const resultBuffer = await documentService.mergeWordDocuments(fileBuffers, {
      preserveFormatting,
      outputFormat
    });

    // 生成文件名
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const fileName = `merged_document_${timestamp}.${outputFormat}`;

    // 保存文件并获取下载URL
    const downloadUrl = await documentService.saveToMinio(resultBuffer, fileName);

    return c.json({
      success: true,
      message: `成功合并 ${files.length} 个文档`,
      fileName,
      fileSize: resultBuffer.length,
      downloadUrl,
      minioAvailable: documentService.isMinioAvailable()
    }, 200);

  } catch (error) {
    console.error('文档合并错误:', error);
    return c.json({ 
      code: 500, 
      message: error instanceof Error ? error.message : '文档合并失败' 
    }, 500);
  }
});

export default app;