import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { SolutionDesignSchema } from '@/server/modules/solution-designs/solution-design.schema';
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 GetParams = z.object({
  id: z.string().openapi({
    param: { name: 'id', in: 'path' },
    example: '1',
    description: '方案设计ID'
  })
});

// 路由定义
const routeDef = createRoute({
  method: 'get',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: GetParams
  },
  responses: {
    200: {
      description: '成功获取方案设计详情',
      content: { 'application/json': { schema: SolutionDesignSchema } }
    },
    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 result = await service.getById(Number(id), ['user', 'originalFile', 'outputFile', 'chapters']);

    if (!result) {
      return c.json({ code: 404, message: '方案设计不存在' }, 404);
    }

    // 检查权限：只能查看自己的方案设计
    if (result.userId !== user.id) {
      return c.json({ code: 403, message: '无权访问此方案设计' }, 403);
    }

    return c.json(result, 200);

  } catch (error) {
    console.error('获取方案设计详情失败:', error);
    const { code = 500, message = '获取详情失败' } = error as Error & { code?: number };
    return c.json({ code, message }, code);
  }
});

export default app;