import { OpenAPIHono } from '@hono/zod-openapi';
import { authMiddleware } from '@d8d/auth-module';
import { AppDataSource } from '@d8d/shared-utils';
import { AuthContext } from '@d8d/shared-types';
import { OrderService } from '../services';
import { CreateOrderRequestDto, CreateOrderResponseDto } from '../schemas/create-order.schema';

const createOrderRoutes = new OpenAPIHono<AuthContext>();

// 应用认证中间件
createOrderRoutes.use('*', authMiddleware);

// 创建订单路由
createOrderRoutes.openapi(
  {
    method: 'post',
    path: '/',
    request: {
      body: {
        content: {
          'application/json': {
            schema: CreateOrderRequestDto
          }
        }
      }
    },
    responses: {
      200: {
        description: '订单创建成功',
        content: {
          'application/json': {
            schema: CreateOrderResponseDto
          }
        }
      },
      400: {
        description: '请求参数错误'
      },
      500: {
        description: '服务器内部错误'
      }
    }
  },
  async (c) => {
    const data = c.req.valid('json');
    const user = c.get('user');

    try {
      const orderService = new OrderService(AppDataSource);
      const result = await orderService.createOrder(data, user.id);

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

export default createOrderRoutes;