import { Body, Controller, Post } from '@nestjs/common';
import { QuizService } from './quiz.service';
import { SubmitQuizDto } from './dto/submit-quiz.dto';
import { ProgressService } from '../progress/progress.service';

/** Learner-facing quiz grading; no authentication (the mobile app has no login). */
@Controller('api/v1/quiz')
export class QuizController {
  constructor(
    private readonly quizService: QuizService,
    private readonly progressService: ProgressService,
  ) {}

  @Post('submit')
  async submit(@Body() dto: SubmitQuizDto) {
    const result = await this.quizService.grade(dto);

    // Recording progress is a convenience, not a precondition for the score.
    if (dto.anonymousSessionId) {
      await this.progressService.upsertProgress(
        dto.anonymousSessionId,
        'activity',
        dto.activityId,
        {
          completed: true,
          type: 'QUIZ',
          score: result.score,
          maxScore: result.maxScore,
          percentage: result.percentage,
          completedAt: new Date().toISOString(),
        },
      );
    }

    return { success: true, message: 'Quiz submitted', data: result };
  }
}
