import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { authMiddleware } from '@d8d/auth-module';
import { AppDataSource, ErrorSchema, parseWithAwait } from '@d8d/shared-utils';
import { AuthContext } from '@d8d/shared-types';
import { OrderRefundSchema, CreateOrderRefundDto, UpdateOrderRefundDto } from '../../schemas/order-refund.schema';
import { UserRefundsService } from '../../services/user-refunds.service';

// 获取当前用户退款列表路由
const getUserRefundsRoute = 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: '搜索关键词'
      }),
      filters: z.string().optional().openapi({
        example: '{"state": 0}',
        description: '过滤条件JSON字符串'
      })
    })
  },
  responses: {
    200: {
      description: '成功获取退款列表',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(OrderRefundSchema),
            pagination: z.object({
              total: z.number(),
              current: z.number(),
              pageSize: z.number()
            })
          })
        }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 获取当前用户退款详情路由
const getUserRefundRoute = 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: OrderRefundSchema }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '无权访问该退款',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '退款不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

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

// 更新当前用户退款路由
const updateUserRefundRoute = 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: UpdateOrderRefundDto }
      }
    }
  },
  responses: {
    200: {
      description: '成功更新退款',
      content: {
        'application/json': { schema: OrderRefundSchema }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '无权更新该退款',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '退款不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 删除当前用户退款路由
const deleteUserRefundRoute = 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(getUserRefundsRoute, async (c) => {
    const user = c.get('user');
    const { page, pageSize, keyword, filters } = c.req.valid('query');

    const refundsService = new UserRefundsService(AppDataSource);
    const [data, total] = await refundsService.getUserRefundsList(
      page,
      pageSize,
      keyword,
      user?.id,
      filters ? JSON.parse(filters) : undefined
    );

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

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

    try {
      const refundsService = new UserRefundsService(AppDataSource);
      const refund = await refundsService.getUserRefundById(id, user?.id);
      if (!refund) {
        return c.json({ code: 404, message: '退款记录不存在' }, 404);
      }

      // 使用 parseWithAwait 确保数据格式正确
      const validatedRefund = await parseWithAwait(OrderRefundSchema, refund);

      return c.json(validatedRefund, 200);
    } catch (error) {
      if (error instanceof Error && error.message.includes('无权')) {
        return c.json({ code: 403, message: error.message }, 403);
      }
      throw error;
    }
  })
  .openapi(createUserRefundRoute, async (c) => {
    const user = c.get('user');
    const data = c.req.valid('json');

    try {
      const refundsService = new UserRefundsService(AppDataSource);
      const refund = await refundsService.createUserRefund(data, user?.id);

      // 使用 parseWithAwait 确保数据格式正确
      const validatedRefund = await parseWithAwait(OrderRefundSchema, refund);

      return c.json(validatedRefund, 201);
    } catch (error) {
      if (error instanceof Error && error.message.includes('无权')) {
        return c.json({ code: 403, message: error.message }, 403);
      }
      throw error;
    }
  })
  .openapi(updateUserRefundRoute, async (c) => {
    const user = c.get('user');
    const { id } = c.req.valid('param');
    const data = c.req.valid('json');

    try {
      const refundsService = new UserRefundsService(AppDataSource);
      const refund = await refundsService.updateUserRefund(id, data, user?.id);
      if (!refund) {
        return c.json({ code: 404, message: '退款记录不存在' }, 404);
      }

      // 使用 parseWithAwait 确保数据格式正确
      const validatedRefund = await parseWithAwait(OrderRefundSchema, refund);

      return c.json(validatedRefund, 200);
    } catch (error) {
      if (error instanceof Error && error.message.includes('无权')) {
        return c.json({ code: 403, message: error.message }, 403);
      }
      throw error;
    }
  })
  .openapi(deleteUserRefundRoute, async (c) => {
    const user = c.get('user');
    const { id } = c.req.valid('param');

    try {
      const refundsService = new UserRefundsService(AppDataSource);
      const success = await refundsService.deleteUserRefund(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;