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';
import { authMiddleware } from '@/server/middleware/auth.middleware';
import { AuthContext } from '@/server/types/context';

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

// 下载响应Schema
const DownloadResponse = z.object({
  downloadUrl: z.string().openapi({
    description: '下载URL',
    example: 'https://example.com/download/template.docx'
  }),
  fileName: z.string().openapi({
    description: '文件名',
    example: '销售合同模板.docx'
  })
});

// 路由定义
const routeDef = createRoute({
  method: 'post',
  path: '/{id}/download',
  middleware: [authMiddleware],
  request: {
    params: DownloadParams
  },
  responses: {
    200: {
      description: '成功获取下载链接',
      content: { 'application/json': { schema: DownloadResponse } }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: z.object({ code: z.number(), message: z.string() }) } }
    },
    403: {
      description: '没有下载权限',
      content: { 'application/json': { schema: z.object({ code: z.number(), message: z.string() }) } }
    },
    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<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const { id } = c.req.valid('param');
    const templateId = parseInt(id);
    const user = c.get('user');

    if (!user) {
      return c.json({ code: 401, message: '请先登录' }, 401);
    }

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

    // 检查下载权限
    const canDownload = await service.checkDownloadPermission(templateId, user.id);
    if (!canDownload) {
      return c.json({ code: 403, message: '需要购买会员才能下载该模板' }, 403);
    }

    // 增加下载次数
    await service.incrementDownloadCount(templateId);

    // 获取下载URL
    let downloadUrl: string;
    try {
      downloadUrl = await template.file.fullUrl;
    } catch (error) {
      console.error('获取文件下载URL失败:', error);
      return c.json({ code: 500, message: '获取文件下载URL失败' }, 500);
    }
    const fileName = template.file.name;

    return c.json({
      downloadUrl,
      fileName
    }, 200);
  } catch (error) {
    const message = error instanceof Error ? error.message : '下载模板失败';
    return c.json({ code: 500, message }, 500);
  }
});

export default app;