import Router from '@koa/router';
import { shareService } from './share.service';
import { authMiddleware } from '../../middleware/auth';

const router = new Router();

/**
 * 获取分享信息（兼容feature_list测试接口）
 * GET /api/share?audioId=xxx
 */
router.get('/', async (ctx) => {
  try {
    const { audioId } = ctx.query as { audioId: string };
    if (!audioId) {
      ctx.body = {
        code: 400,
        message: 'audioId is required',
      };
      return;
    }
    const card = await shareService.generateShareCard(audioId);

    ctx.body = {
      code: 0,
      message: 'success',
      data: card,
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '获取分享信息失败',
    };
  }
});

/**
 * 获取分享卡片信息
 * GET /api/share/card/:audioId
 */
router.get('/card/:audioId', async (ctx) => {
  try {
    const { audioId } = ctx.params;
    const card = await shareService.generateShareCard(audioId);

    ctx.body = {
      code: 0,
      message: 'success',
      data: card,
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '获取分享信息失败',
    };
  }
});

/**
 * 生成二维码数据
 * GET /api/share/qrcode/:audioId
 */
router.get('/qrcode/:audioId', async (ctx) => {
  try {
    const { audioId } = ctx.params;
    const qrData = shareService.generateQRCodeData(audioId);
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        text: qrData,
      },
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '生成二维码失败',
    };
  }
});

/**
 * 记录分享行为
 * POST /api/share/track
 */
router.post('/track', authMiddleware, async (ctx) => {
  try {
    const { audioId, platform } = ctx.request.body as { audioId: string; platform: string };
    const userId = (ctx.state as any).user.id;
    
    await shareService.trackShare(audioId, userId, platform);
    
    ctx.body = {
      code: 0,
      message: 'success',
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '记录分享失败',
    };
  }
});

export default router;
