import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { authMiddleware } from '../../middleware/auth.middleware';
import { OrderService } from '../../modules/orders/order.service';
import { OrderListSchema, 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';

// 订单列表响应Schema
export const OrderListResponseSchema = z.object({
  data: z.array(OrderResponseSchema),
  total: z.number(),
  page: z.number(),
  pageSize: z.number()
});

// 订单列表路由定义
const listOrdersRoute = createRoute({
  method: 'get',
  path: '/',
  middleware: [authMiddleware],
  request: {
    query: OrderListSchema
  },
  responses: {
    200: {
      description: '订单列表获取成功',
      content: { 'application/json': { schema: OrderListResponseSchema } }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '未授权',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(listOrdersRoute, async (c) => {
    try {
      const user = c.get('user');
      const queryParams = c.req.valid('query');
      const { page, pageSize, status, paymentStatus, search } = queryParams;

      const orderService = new OrderService();

      // 使用服务方法获取用户订单
      const response = await orderService.getUserOrders(user.id, {
        status,
        paymentStatus,
        page,
        pageSize
      });

      return c.json(await parseWithAwait(OrderListResponseSchema, response), 200);
    } catch (error) {
      console.error('获取订单列表失败:', error);
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取订单列表失败'
      }, 500);
    }
  });

export default app;