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

// 订单取消路由定义
const cancelOrderRoute = createRoute({
  method: 'post',
  path: '/{id}/cancel',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number<number>().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '订单ID'
      })
    })
  },
  responses: {
    200: {
      description: '订单取消成功',
      content: { 'application/json': { schema: OrderResponseSchema } }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '未授权',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      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(cancelOrderRoute, async (c) => {
    try {
      const user = c.get('user');
      const { id } = c.req.valid('param');

      const orderService = new OrderService();
      const order = await orderService.cancelOrder(user.id, id);

      return c.json(await parseWithAwait(OrderResponseSchema, order), 200);
    } catch (error) {
      console.error('订单取消失败:', error);

      // 根据错误类型返回不同的状态码
      const errorMessage = error instanceof Error ? error.message : '订单取消失败';

      if (errorMessage.includes('订单不存在')) {
        return c.json({
          code: 404,
          message: errorMessage
        }, 404);
      }

      if (errorMessage.includes('权限不足')) {
        return c.json({
          code: 403,
          message: errorMessage
        }, 403);
      }

      if (errorMessage.includes('只能取消待出发状态的订单') ||
          errorMessage.includes('距离出发时间不足1小时')) {
        return c.json({
          code: 422,
          message: errorMessage
        }, 422);
      }

      return c.json({
        code: 500,
        message: errorMessage
      }, 500);
    }
  });

export default app;