import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { authMiddleware } from '../../middleware/auth.middleware';
import { OrderService } from '../../modules/orders/order.service';
import { OrderCreateSchema, OrderResponseSchema } from '../../modules/orders/order.schema';
import { RouteService } from '../../modules/routes/route.service';
import { PassengerService } from '../../modules/passengers/passenger.service';
import { AuthContext } from '../../types/context';
import { AppDataSource } from '../../data-source';
import { ErrorSchema } from '../../utils/errorHandler';
import { parseWithAwait } from '../../utils/parseWithAwait';

// 订单创建路由定义
const createOrderRoute = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: OrderCreateSchema }
      }
    }
  },
  responses: {
    201: {
      description: '订单创建成功',
      content: { 'application/json': { schema: OrderResponseSchema } }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '未授权',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '路线或乘客不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    422: {
      description: '业务逻辑错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(createOrderRoute, async (c) => {
    try {
      const user = c.get('user');
      const orderData = c.req.valid('json');

      // 验证路线是否存在
      const routeService = new RouteService(AppDataSource);
      const route = await routeService.getRouteById(orderData.routeId);
      if (!route) {
        return c.json({
          code: 404,
          message: '路线不存在'
        }, 404);
      }

      // 验证乘客数量不超过路线座位数
      if (orderData.passengerCount > route.availableSeats) {
        return c.json({
          code: 422,
          message: `乘客数量超过路线座位数，当前路线剩余座位：${route.availableSeats}`
        }, 422);
      }

      // 验证乘客快照信息
      const passengerService = new PassengerService();
      for (const passengerSnapshot of orderData.passengerSnapshots) {
        if (passengerSnapshot.id) {
          const passenger = await passengerService.getPassengerById(passengerSnapshot.id);
          if (!passenger) {
            return c.json({
              code: 404,
              message: `乘客ID ${passengerSnapshot.id} 不存在`
            }, 404);
          }
        }
      }

      // 创建订单
      const orderService = new OrderService();
      const order = await orderService.createOrder(user.id, orderData);

      return c.json(await parseWithAwait(OrderResponseSchema, order), 201);
    } catch (error) {
      console.error('订单创建失败:', error);
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '订单创建失败'
      }, 500);
    }
  });

export default app;