import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { CreateSolutionDesignDto } from '@/server/modules/solution-designs/solution-design.schema';
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';

// 路由定义
const routeDef = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateSolutionDesignDto }
      }
    }
  },
  responses: {
    200: {
      description: '成功创建方案设计',
      content: { 'application/json': { schema: SolutionDesignSchema } }
    },
    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 data = await c.req.json();
    const user = c.get('user');
    
    const service = new SolutionDesignService(AppDataSource);
    const result = await service.createSolutionDesign(data, user.id, data.originalFileId);

    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;