import Router from '@koa/router';
import { commentsService } from './comments.service';

const router = new Router({ prefix: '/api/comments' });

// 测试用户ID
const TEST_USER_ID = 1;

/**
 * 获取章节评论
 * GET /api/comments/:chapterId
 */
router.get('/:chapterId', async (ctx) => {
  try {
    const chapterId = parseInt(ctx.params.chapterId);
    const comments = await commentsService.getCommentsByChapterId(chapterId);

    ctx.body = {
      code: 0,
      message: 'success',
      data: comments,
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '获取评论失败',
    };
  }
});

/**
 * 添加评论
 * POST /api/comments
 */
router.post('/', async (ctx) => {
  try {
    const { chapterId, content, rating } = ctx.request.body as {
      chapterId: number;
      content: string;
      rating: number;
    };

    const comment = await commentsService.addComment(TEST_USER_ID, chapterId, content, rating);

    ctx.body = {
      code: 0,
      message: '评论成功',
      data: comment,
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '评论失败',
    };
  }
});

export default router;
