import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { CreateOrderRequestDto, CreateOrderResponseDto } from '../../modules/orders/schemas/create-order.schema';
import { ErrorSchema } from '../../utils/errorHandler';
import { AppDataSource } from '../../data-source';
import { OrderService } from '../../modules/orders/order.service';
import { AuthContext } from '../../types/context';
import { authMiddleware } from '../../middleware/auth.middleware';

const routeDef = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': {
          schema: CreateOrderRequestDto
        }
      }
    }
  },
  responses: {
    200: {
      description: '订单创建成功',
      content: {
        'application/json': {
          schema: CreateOrderResponseDto
        }
      }
    },
    400: {
      description: '请求参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const data = await c.req.json();
    const user = c.get('user');

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

    return c.json({
      success: true,
      orderId: result.orderId,
      orderNo: result.orderNo,
      amount: result.amount,
      payAmount: result.payAmount,
      message: '订单创建成功'
    }, 200);
  } catch (error) {
    const message = error instanceof Error ? error.message : '创建订单失败';
    return c.json({ code: 500, message }, 500);
  }
});

export default app;