import { Controller, Get, Post, Body, Param, Query } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { QuizService } from './quiz.service';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import type { UserPayload } from '../../common/types';

@ApiTags('quiz')
@Controller('quizzes')
export class QuizController {
  constructor(private readonly service: QuizService) {}

  @Post()
  @ApiOperation({ summary: '生成测验' })
  async create(@CurrentUser() user: UserPayload, @Body() dto: any) {
    return this.service.create(String(user?.id || 'anonymous'), dto);
  }

  @Get()
  @ApiOperation({ summary: '测验列表' })
  async findAll(@CurrentUser() user: UserPayload, @Query('knowledgeBaseId') kbId?: string) {
    return this.service.findAll(String(user?.id || 'anonymous'), kbId);
  }

  @Get(':id')
  @ApiOperation({ summary: '测验详情' })
  async findOne(@CurrentUser() user: UserPayload, @Param('id') id: string) {
    return this.service.findOne(String(user?.id || 'anonymous'), id);
  }

  // M-QUIZ-01-01: 创建独立 Attempt
  @Post(':id/attempts')
  @ApiOperation({ summary: '开始答题（创建 Attempt）' })
  async startAttempt(@CurrentUser() user: UserPayload, @Param('id') id: string) {
    return this.service.start(String(user?.id || 'anonymous'), id);
  }

  // 保留旧端点兼容
  @Post(':id/start')
  @ApiOperation({ summary: '开始答题（兼容旧端点）' })
  async start(@CurrentUser() user: UserPayload, @Param('id') id: string) {
    return this.service.start(String(user?.id || 'anonymous'), id);
  }

  // M-QUIZ-01-01: 按 Attempt 加载脱敏题目
  @Get('attempts/:id/questions')
  @ApiOperation({ summary: '获取 Attempt 题目（未提交不返回答案）' })
  async getAttemptQuestions(@CurrentUser() user: UserPayload, @Param('id') attemptId: string) {
    return this.service.getAttemptQuestions(String(user?.id || 'anonymous'), attemptId);
  }

  @Post(':id/submit')
  @ApiOperation({ summary: '提交答案' })
  async submit(@CurrentUser() user: UserPayload, @Param('id') id: string, @Body() dto: { attemptId: string; answers: { questionId: string; answer: string }[] }) {
    return this.service.submit(String(user?.id || 'anonymous'), dto.attemptId, dto.answers);
  }

  // M-QUIZ-01-01: 结果查询增加 userId 校验
  @Get(':id/results')
  @ApiOperation({ summary: '测验结果' })
  async getResults(@CurrentUser() user: UserPayload, @Param('id') id: string, @Query('attemptId') attemptId: string) {
    return this.service.getResults(String(user?.id || 'anonymous'), attemptId);
  }

  @Get('history/list')
  @ApiOperation({ summary: '测验历史' })
  async getHistory(@CurrentUser() user: UserPayload) {
    return this.service.getHistory(String(user?.id || 'anonymous'));
  }
}
