import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { authMiddleware } from '@d8d/auth-module-mt';
import { AppDataSource, ErrorSchema } from '@d8d/shared-utils';
import { AuthContext } from '@d8d/shared-types';
import { OrderMtService } from '../../services';
import { CancelOrderRequestDto, CancelOrderResponseDto } from '../../schemas/cancel-order.schema';

const cancelOrderRoute = createRoute({
  method: 'post',
  path: '/cancel-order',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': {
          schema: CancelOrderRequestDto
        }
      }
    }
  },
  responses: {
    200: {
      description: '订单取消成功',
      content: {
        'application/json': {
          schema: CancelOrderResponseDto
        }
      }
    },
    400: {
      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 cancelOrderRoutes = new OpenAPIHono<AuthContext>()
  // 取消订单路由
  .openapi( cancelOrderRoute, async (c) => {
      const data = c.req.valid('json');
      const user = c.get('user');

      try {
        const orderService = new OrderMtService(AppDataSource);
        await orderService.cancelOrder(user.tenantId, data.orderId, data.reason, user.id);

        return c.json({
          success: true,
          message: '订单取消成功'
        }, 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 cancelOrderRoutes;