import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { authMiddleware } from '@d8d/auth-module-mt';
import { AppDataSource, ErrorSchema, parseWithAwait } from '@d8d/shared-utils';
import { AuthContext } from '@d8d/shared-types';
import { OrderGoodsSchema, CreateOrderGoodsDto, UpdateOrderGoodsDto } from '../../schemas/order-goods.schema';
import { UserOrderGoodsMtService } from '../../services/user-order-goods.mt.service';

// 获取当前用户订单商品列表路由
const getUserOrderItemsRoute = createRoute({
  method: 'get',
  path: '/',
  middleware: [authMiddleware],
  request: {
    query: z.object({
      page: z.coerce.number().int().positive('页码必须是正整数').default(1).openapi({
        example: 1,
        description: '页码，从1开始'
      }),
      pageSize: z.coerce.number().int().positive('每页数量必须是正整数').default(10).openapi({
        example: 10,
        description: '每页数量'
      }),
      keyword: z.string().optional().openapi({
        example: '搜索关键词',
        description: '搜索关键词'
      })
    })
  },
  responses: {
    200: {
      description: '成功获取订单商品列表',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(OrderGoodsSchema),
            pagination: z.object({
              total: z.number(),
              current: z.number(),
              pageSize: z.number()
            })
          })
        }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 获取当前用户订单商品详情路由
const getUserOrderItemRoute = createRoute({
  method: 'get',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().int().positive('ID必须是正整数').openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '订单商品ID'
      })
    })
  },
  responses: {
    200: {
      description: '成功获取订单商品详情',
      content: {
        'application/json': { schema: OrderGoodsSchema }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '无权访问该订单商品',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单商品不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 为当前用户创建订单商品路由
const createUserOrderItemRoute = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateOrderGoodsDto }
      }
    }
  },
  responses: {
    201: {
      description: '成功创建订单商品',
      content: {
        'application/json': { schema: OrderGoodsSchema }
      }
    },
    400: {
      description: '请求参数验证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '无权为该订单创建商品',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 更新当前用户订单商品路由
const updateUserOrderItemRoute = createRoute({
  method: 'put',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().int().positive('ID必须是正整数').openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '订单商品ID'
      })
    }),
    body: {
      content: {
        'application/json': { schema: UpdateOrderGoodsDto }
      }
    }
  },
  responses: {
    200: {
      description: '成功更新订单商品',
      content: {
        'application/json': { schema: OrderGoodsSchema }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '无权更新该订单商品',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单商品不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 删除当前用户订单商品路由
const deleteUserOrderItemRoute = createRoute({
  method: 'delete',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().int().positive('ID必须是正整数').openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '订单商品ID'
      })
    })
  },
  responses: {
    204: { description: '成功删除订单商品' },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '无权删除该订单商品',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单商品不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(getUserOrderItemsRoute, async (c) => {
    const user = c.get('user');
    const { page, pageSize, keyword } = c.req.valid('query');

    const orderGoodsService = new UserOrderGoodsMtService(AppDataSource);
    const [data, total] = await orderGoodsService.getUserOrderGoodsList(
      page,
      pageSize,
      keyword,
      user?.id
    );

    // 使用 parseWithAwait 确保数据格式正确
    const validatedData = await parseWithAwait(z.array(OrderGoodsSchema), data);

    return c.json({
      data: validatedData,
      pagination: { total, current: page, pageSize: pageSize }
    }, 200);
  })
  .openapi(getUserOrderItemRoute, async (c) => {
    const user = c.get('user');
    const { id } = c.req.valid('param');

    try {
      const orderGoodsService = new UserOrderGoodsMtService(AppDataSource);
      const orderGoods = await orderGoodsService.getUserOrderGoodsById(id, user?.id);
      if (!orderGoods) {
        return c.json({ code: 404, message: '订单商品不存在' }, 404);
      }

      // 使用 parseWithAwait 确保数据格式正确
      const validatedData = await parseWithAwait(OrderGoodsSchema, orderGoods);
      return c.json(validatedData, 200);
    } catch (error) {
      if (error instanceof Error && error.message.includes('无权')) {
        return c.json({ code: 403, message: error.message }, 403);
      }
      throw error;
    }
  })
  .openapi(createUserOrderItemRoute, async (c) => {
    const user = c.get('user');
    const data = c.req.valid('json');

    try {
      const orderGoodsService = new UserOrderGoodsMtService(AppDataSource);
      const orderGoods = await orderGoodsService.createUserOrderGoods(data, user?.id);
      // 使用 parseWithAwait 确保数据格式正确
      const validatedData = await parseWithAwait(OrderGoodsSchema, orderGoods);
      return c.json(validatedData, 201);
    } catch (error) {
      if (error instanceof Error && error.message.includes('无权')) {
        return c.json({ code: 403, message: error.message }, 403);
      }
      throw error;
    }
  })
  .openapi(updateUserOrderItemRoute, async (c) => {
    const user = c.get('user');
    const { id } = c.req.valid('param');
    const data = c.req.valid('json');

    try {
      const orderGoodsService = new UserOrderGoodsMtService(AppDataSource);
      const orderGoods = await orderGoodsService.updateUserOrderGoods(id, data, user?.id);
      if (!orderGoods) {
        return c.json({ code: 404, message: '订单商品不存在' }, 404);
      }

      // 使用 parseWithAwait 确保数据格式正确
      const validatedData = await parseWithAwait(OrderGoodsSchema, orderGoods);
      return c.json(validatedData, 200);
    } catch (error) {
      if (error instanceof Error && error.message.includes('无权')) {
        return c.json({ code: 403, message: error.message }, 403);
      }
      throw error;
    }
  })
  .openapi(deleteUserOrderItemRoute, async (c) => {
    const user = c.get('user');
    const { id } = c.req.valid('param');

    try {
      const orderGoodsService = new UserOrderGoodsMtService(AppDataSource);
      const success = await orderGoodsService.deleteUserOrderGoods(id, user?.id);
      if (!success) {
        return c.json({ code: 404, message: '订单商品不存在' }, 404);
      }

      return c.body(null, 204);
    } catch (error) {
      if (error instanceof Error && error.message.includes('无权')) {
        return c.json({ code: 403, message: error.message }, 403);
      }
      throw error;
    }
  });

export default app;