import Router from '@koa/router';
import { Context } from 'koa';
import * as MemberService from './member.service';
import { BadRequestError, NotFoundError } from '../../middleware/errorHandler';
import { authMiddleware } from '../../middleware/auth';

const router = new Router();

// 获取会员权益信息
router.get('/benefits', async (ctx: Context) => {
  const benefits = MemberService.getMemberBenefits();

  ctx.body = {
    code: 0,
    message: 'success',
    data: benefits,
  };
});

// 获取用户会员状态
router.get('/status', authMiddleware, async (ctx: Context) => {
  const userId = ctx.state.user.userId;
  const status = await MemberService.getMemberStatus(userId);

  ctx.body = {
    code: 0,
    message: 'success',
    data: status,
  };
});

// 创建订单
router.post('/order', authMiddleware, async (ctx: Context) => {
  const userId = ctx.state.user.userId;
  const { productType } = ctx.request.body as { productType: 'monthly' | 'yearly' };

  if (!['monthly', 'yearly'].includes(productType)) {
    throw new BadRequestError('无效的产品类型');
  }

  const result = await MemberService.createOrder(userId, productType);

  ctx.body = {
    code: 0,
    message: '订单创建成功',
    data: result,
  };
});

// 模拟支付（仅开发环境）
router.post('/pay/mock', authMiddleware, async (ctx: Context) => {
  if (process.env.NODE_ENV === 'production') {
    throw new BadRequestError('生产环境不可用');
  }

  const userId = ctx.state.user.userId;
  const { orderNo } = ctx.request.body as { orderNo: string };

  if (!orderNo) {
    throw new BadRequestError('订单号不能为空');
  }

  const result = await MemberService.mockPaymentSuccess(orderNo, userId);

  ctx.body = {
    code: 0,
    message: '支付成功',
    data: result,
  };
});

// 获取订单列表
router.get('/orders', authMiddleware, async (ctx: Context) => {
  const userId = ctx.state.user.userId;
  const { page = 1, pageSize = 10 } = ctx.query as { page?: string; pageSize?: string };

  const result = await MemberService.getOrders(
    userId,
    Number(page) || 1,
    Number(pageSize) || 10
  );

  ctx.body = {
    code: 0,
    message: 'success',
    data: result,
  };
});

export default router;