import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { AppDataSource } from '@/server/data-source';
import { TemplateService } from '@/server/modules/templates/template.service';

// 路径参数Schema
const PreviewParams = z.object({
  id: z.string().openapi({
    param: { name: 'id', in: 'path' },
    example: '1',
    description: '模板ID'
  })
});

// 预览响应Schema
const PreviewResponse = z.object({
  previewUrl: z.string().openapi({
    description: '预览URL',
    example: 'https://example.com/preview/template.docx'
  }),
  template: z.object({
    id: z.number().openapi({ description: '模板ID', example: 1 }),
    title: z.string().openapi({ description: '模板标题', example: '销售合同模板' }),
    description: z.string().nullable().openapi({ description: '模板描述' }),
    category: z.string().openapi({ description: '分类', example: '合同' }),
    isFree: z.number().openapi({ description: '是否免费', example: 0 }),
    downloadCount: z.number().openapi({ description: '下载次数', example: 100 })
  })
});

// 路由定义
const routeDef = createRoute({
  method: 'get',
  path: '/{id}/preview',
  request: {
    params: PreviewParams
  },
  responses: {
    200: {
      description: '成功获取预览信息',
      content: { 'application/json': { schema: PreviewResponse } }
    },
    404: {
      description: '模板不存在',
      content: { 'application/json': { schema: z.object({ code: z.number(), message: z.string() }) } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: z.object({ code: z.number(), message: z.string() }) } }
    }
  }
});

// 路由实现
const app = new OpenAPIHono().openapi(routeDef, async (c) => {
  try {
    const { id } = c.req.valid('param');
    const templateId = parseInt(id);

    const service = new TemplateService(AppDataSource);
    
    // 检查模板是否存在
    const template = await service.getById(templateId, ['file']);
    if (!template) {
      return c.json({ code: 404, message: '模板不存在' }, 404);
    }

    // 检查模板是否可用
    if (template.isDisabled || template.isDeleted) {
      return c.json({ code: 404, message: '模板不可用' }, 404);
    }

    // 构建预览URL（这里可以集成Office Online或其他预览服务）
    let previewUrl = template.previewUrl;
    
    // 如果没有配置预览URL，使用文件URL
    if (!previewUrl) {
      try {
        previewUrl = await template.file.fullUrl;
      } catch (error) {
        console.error('获取文件URL失败:', error);
        // 如果获取文件URL失败，返回错误信息
        return c.json({ code: 500, message: '获取文件预览URL失败' }, 500);
      }
    }

    return c.json({
      previewUrl,
      template: {
        id: template.id,
        title: template.title,
        description: template.description,
        category: template.category,
        isFree: template.isFree,
        downloadCount: template.downloadCount
      }
    }, 200);
  } catch (error) {
    const message = error instanceof Error ? error.message : '获取预览信息失败';
    return c.json({ code: 500, message }, 500);
  }
});

export default app;