package com.ycwl.basic.controller.mobile;

import com.ycwl.basic.annotation.IgnoreToken;
import com.ycwl.basic.constant.BaseContextHandler;
import com.ycwl.basic.integration.questionnaire.dto.answer.ResponseDetailResponse;
import com.ycwl.basic.integration.questionnaire.dto.answer.SubmitAnswerRequest;
import com.ycwl.basic.integration.questionnaire.dto.questionnaire.QuestionnaireResponse;
import com.ycwl.basic.integration.questionnaire.service.QuestionnaireIntegrationService;
import com.ycwl.basic.utils.ApiResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 移动端问卷接口控制器
 * 
 * @author Claude Code
 * @date 2025-09-05
 */
@Slf4j
@RestController
@RequestMapping("/api/mobile/questionnaire/v1")
@RequiredArgsConstructor
public class AppQuestionnaireController {

    private final QuestionnaireIntegrationService questionnaireIntegrationService;

    /**
     * 获取问卷详情
     * 包含问卷基本信息和所有题目
     */
    @IgnoreToken
    @GetMapping("/{id}")
    public ApiResponse<QuestionnaireResponse> getQuestionnaire(@PathVariable Long id) {
        log.info("移动端获取问卷详情, id: {}", id);
        try {
            QuestionnaireResponse questionnaire = questionnaireIntegrationService.getQuestionnaire(id);
            
            // 检查问卷状态，只有已发布的问卷才能被移动端访问
            if (questionnaire.getStatus() != 2) {
                return ApiResponse.fail("问卷未发布或已停止");
            }
            
            return ApiResponse.success(questionnaire);
        } catch (Exception e) {
            log.error("移动端获取问卷详情失败, id: {}", id, e);
            return ApiResponse.fail("获取问卷详情失败: " + e.getMessage());
        }
    }

    /**
     * 提交问卷答案
     */
    @PostMapping("/{id}/submit")
    public ApiResponse<ResponseDetailResponse> submitAnswer(
            @PathVariable Long id,
            @Valid @RequestBody SubmitAnswerRequest request) {
        
        String userId = BaseContextHandler.getUserId();
        log.info("移动端提交问卷答案, questionnaireId: {}, userId: {}, answers count: {}", 
                id, userId, request.getAnswers() != null ? request.getAnswers().size() : 0);
        
        try {
            // 设置问卷ID和用户ID
            request.setQuestionnaireId(id);
            request.setUserId(userId);
            
            ResponseDetailResponse response = questionnaireIntegrationService.submitAnswer(request);
            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("移动端提交问卷答案失败, questionnaireId: {}, userId: {}", id, userId, e);
            return ApiResponse.fail("提交问卷答案失败: " + e.getMessage());
        }
    }
}