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

// 路径参数Schema
const GenerateParams = z.object({
  id: z.string().openapi({
    param: { name: 'id', in: 'path' },
    example: '1',
    description: '方案设计ID'
  })
});

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

// 路由定义
const routeDef = createRoute({
  method: 'post',
  path: '/{id}/generate',
  middleware: [authMiddleware],
  request: {
    params: GenerateParams
  },
  responses: {
    200: {
      description: '成功生成最终文档',
      content: { 'application/json': { schema: GenerateResponse } }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '方案设计不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 路由实现
const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const { id } = c.req.valid('param');
    const user = c.get('user');
    
    const service = new SolutionDesignService(AppDataSource);
    
    // 先检查权限
    const existingDesign = await service.getById(Number(id));
    if (!existingDesign) {
      return c.json({ code: 404, message: '方案设计不存在' }, 404);
    }

    if (existingDesign.userId !== user.id) {
      return c.json({ code: 403, message: '无权操作此方案设计' }, 403);
    }

    // 生成最终文档
    const documentBuffer = await service.generateFinalDocument(Number(id));
    
    // 保存文档并获取下载URL
    const downloadUrl = await service.saveFinalDocument(Number(id), documentBuffer);

    return c.json({
      success: true,
      message: '文档生成成功',
      downloadUrl,
      fileName: `solution_${id}.${existingDesign.outputFormat}`,
      fileSize: documentBuffer.length
    }, 200);

  } catch (error) {
    console.error('生成文档失败:', error);
    const { code = 500, message = error.message || '生成文档失败' } = error as Error & { code?: number };
    return c.json({ code, message }, code);
  }
});

export default app;