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 userId = (ctx.state as any).user?.id;
    const card = await shareService.generateShareCard(audioId, userId ? parseInt(userId) : undefined);

    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, shareCode } = ctx.request.body as { audioId: string; platform: string; shareCode?: string };
    const userId = (ctx.state as any).user.id;

    const record = await shareService.trackShare(userId, parseInt(audioId), platform, shareCode);

    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        id: record.id,
        shareCode: record.shareCode,
      },
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '记录分享失败',
    };
  }
});

/**
 * 通过分享码追踪访问
 * GET /api/share/visit?code=xxx
 */
router.get('/visit', async (ctx) => {
  try {
    const { code } = ctx.query as { code: string };
    if (!code) {
      ctx.status = 400;
      ctx.body = { code: -1, message: '缺少分享码参数' };
      return;
    }

    const record = await shareService.trackShareVisit(code as string);
    ctx.body = {
      code: 0,
      data: {
        valid: !!record,
        sharer: record ? { id: record.userId, nickname: record.user?.nickname } : null,
      },
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '追踪访问失败',
    };
  }
});

export default router;