import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { UpdateSolutionDesignDto } 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';

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

// 路由定义
const routeDef = createRoute({
  method: 'put',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: UpdateParams,
    body: {
      content: {
        'application/json': { schema: UpdateSolutionDesignDto }
      }
    }
  },
  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 data = await c.req.json();
    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 result = await service.update(Number(id), data);

    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;