import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { authMiddleware } from '../../../middleware/auth.middleware';
import { OrderService } from '../../../modules/orders/order.service';
import { OrderResponseSchema } from '../../../modules/orders/order.schema';
import { AuthContext } from '../../../types/context';
import { ErrorSchema } from '../../../utils/errorHandler';
import { parseWithAwait } from '../../../utils/parseWithAwait';
import { z } from 'zod';

// 订单详情路由定义
const getOrderRoute = createRoute({
  method: 'get',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number<number>().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '订单ID'
      })
    })
  },
  responses: {
    200: {
      description: '订单详情获取成功',
      content: { 'application/json': { schema: OrderResponseSchema } }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '未授权',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      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(getOrderRoute, async (c) => {
    try {
      const user = c.get('user');
      const { id } = c.req.valid('param');

      const orderService = new OrderService();

      // 使用服务方法获取订单详情
      const order = await orderService.getOrderDetail(user.id, id);

      return c.json(await parseWithAwait(OrderResponseSchema, order), 200);
    } catch (error) {
      console.error('获取订单详情失败:', error);

      // 根据错误类型返回不同的状态码
      if (error instanceof Error) {
        if (error.message === '订单不存在') {
          return c.json({
            code: 404,
            message: error.message
          }, 404);
        } else if (error.message === '权限不足，只能查看自己的订单') {
          return c.json({
            code: 403,
            message: error.message
          }, 403);
        }
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取订单详情失败'
      }, 500);
    }
  });

export default app;