package com.dne.ems.controller;

import java.time.LocalDate;


import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.dne.ems.dto.FeedbackResponseDTO;
import com.dne.ems.dto.FeedbackStatsResponse;
import com.dne.ems.dto.FeedbackSubmissionRequest;
import com.dne.ems.dto.ProcessFeedbackRequest;
import com.dne.ems.model.Feedback;
import com.dne.ems.model.enums.FeedbackStatus;
import com.dne.ems.model.enums.PollutionType;
import com.dne.ems.model.enums.SeverityLevel;
import com.dne.ems.security.CustomUserDetails;
import com.dne.ems.service.FeedbackService;

import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;

/**
 * 公众反馈控制器，处理环境问题反馈的提交、查询和统计
 *
 * <p>主要功能包括：
 * <ul>
 *   <li>公众环境问题反馈提交（支持认证用户和匿名用户）</li>
 *   <li>反馈信息查询与多条件过滤</li>
 *   <li>反馈数据统计分析</li>
 *   <li>反馈状态流转管理</li>
 * </ul>
 *
 * <p>权限控制：
 * <ul>
 *   <li>提交接口：所有认证用户</li>
 *   <li>查询接口：管理员、主管、决策者</li>
 * </ul>
 *
 * @author DNE开发团队
 * @version 1.0
 * @since 2024-03
 * @see com.dne.ems.dto.FeedbackSubmissionRequest 反馈提交请求DTO
 * @see com.dne.ems.model.enums.FeedbackStatus 反馈状态枚举
 */
@RestController
@RequestMapping("/api/feedback")
@RequiredArgsConstructor
public class FeedbackController {

    private final FeedbackService feedbackService;

    /**
     * 提交反馈(JSON格式，仅用于测试)
     *
     * <p>此接口用于测试目的，使用application/json格式提交反馈数据，
     * 比multipart/form-data格式更便于使用curl等工具测试。
     * 正式接口请使用 {@link #submitFeedback(FeedbackSubmissionRequest, MultipartFile[], CustomUserDetails)}
     *
     * @param request 包含反馈信息的请求体
     * @param userDetails 当前认证用户信息
     * @return 创建成功的反馈实体和201状态码
     * @throws IllegalArgumentException 如果请求参数无效
     * @see FeedbackSubmissionRequest
     */
    @PostMapping(value = "/submit-json")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<Feedback> submitFeedbackJson(
            @Valid @RequestBody FeedbackSubmissionRequest request,
            @AuthenticationPrincipal CustomUserDetails userDetails) {
        
        Feedback createdFeedback = feedbackService.submitFeedback(request, null); // No files for this endpoint
        return new ResponseEntity<>(createdFeedback, HttpStatus.CREATED);
    }

    /**
     * 提交反馈(正式接口)
     *
     * <p>使用multipart/form-data格式提交反馈，支持附件上传
     *
     * @param request 包含反馈信息的请求体
     * @param files 可选的上传附件
     * @param userDetails 当前认证用户信息
     * @return 创建成功的反馈实体和201状态码
     * @throws IllegalArgumentException 如果请求参数无效
     * @throws FileStorageException 如果文件上传失败
     * @see FeedbackSubmissionRequest
     */
    @PostMapping(value = "/submit", consumes = {"multipart/form-data"})
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<Feedback> submitFeedback(
            @Valid @RequestPart("feedback") FeedbackSubmissionRequest request,
            @RequestPart(value = "files", required = false) MultipartFile[] files,
            @AuthenticationPrincipal CustomUserDetails userDetails) {
        
        Feedback createdFeedback = feedbackService.submitFeedback(request, files);
        return new ResponseEntity<>(createdFeedback, HttpStatus.CREATED);
    }

    /**
     * 获取所有反馈(分页+多条件过滤)
     *
     * <p>支持以下过滤条件组合查询：
     * <ul>
     *   <li>状态：PENDING_REVIEW(待审核)/PROCESSED(已处理)/REJECTED(已拒绝)</li>
     *   <li>污染类型：AIR/WATER/SOIL/NOISE等</li>
     *   <li>严重程度：LOW/MEDIUM/HIGH/CRITICAL</li>
     *   <li>地理位置：城市/区县</li>
     *   <li>时间范围：开始日期至结束日期</li>
     *   <li>关键词：标题/描述模糊匹配</li>
     * </ul>
     *
     * @param userDetails 当前认证用户信息
     * @param status 反馈状态过滤条件
     * @param pollutionType 污染类型过滤条件
     * @param severityLevel 严重程度过滤条件
     * @param cityName 城市名称过滤条件
     * @param districtName 区县名称过滤条件
     * @param startDate 开始日期过滤条件(ISO格式:yyyy-MM-dd)
     * @param endDate 结束日期过滤条件(ISO格式:yyyy-MM-dd)
     * @param keyword 关键词过滤条件(模糊匹配)
     * @param pageable 分页参数(页号从0开始)
     * @return 符合条件的反馈列表(分页)
     * @see com.dne.ems.model.Feedback 反馈实体
     * @see com.dne.ems.model.enums.FeedbackStatus 反馈状态枚举
     * @see com.dne.ems.model.enums.PollutionType 污染类型枚举
     * @see com.dne.ems.model.enums.SeverityLevel 严重程度枚举
     */
    @GetMapping
    @PreAuthorize("isAuthenticated()")
    @Operation(summary = "Get all feedback", description = "Retrieves a paginated list of all feedback submissions with filtering options.")
    public ResponseEntity<Page<FeedbackResponseDTO>> getAllFeedback(
            @AuthenticationPrincipal CustomUserDetails userDetails,
            @RequestParam(required = false) FeedbackStatus status,
            @RequestParam(required = false) PollutionType pollutionType,
            @RequestParam(required = false) SeverityLevel severityLevel,
            @RequestParam(required = false) String cityName,
            @RequestParam(required = false) String districtName,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(required = false) String keyword,
            Pageable pageable) {
        
        Page<FeedbackResponseDTO> feedbackPage = feedbackService.getFeedback(
                userDetails, status, pollutionType, severityLevel, cityName, districtName, 
                startDate, endDate, keyword, pageable);
        
        return ResponseEntity.ok(feedbackPage);
    }

    /**
     * 根据ID获取反馈详情
     *
     * @param id 反馈ID
     * @return 反馈详情实体
     * @throws ResourceNotFoundException 如果反馈不存在
     * @see Feedback
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERVISOR', 'DECISION_MAKER')")
    @Operation(summary = "Get feedback by ID", description = "Retrieves feedback details by ID.")
    public ResponseEntity<FeedbackResponseDTO> getFeedbackById(@PathVariable Long id) {
        FeedbackResponseDTO feedback = feedbackService.getFeedbackDetail(id);
        return ResponseEntity.ok(feedback);
    }
    
    /**
     * 获取反馈统计数据
     *
     * @param userDetails 当前认证用户信息
     * @return 包含各类反馈统计数据的响应实体
     * @see FeedbackStatsResponse
     */
    @GetMapping("/stats")
    @PreAuthorize("isAuthenticated()")
    @Operation(summary = "Get feedback statistics", description = "Retrieves statistics about feedback status counts.")
    public ResponseEntity<FeedbackStatsResponse> getFeedbackStats(@AuthenticationPrincipal CustomUserDetails userDetails) {
        FeedbackStatsResponse stats = feedbackService.getFeedbackStats(userDetails);
        return ResponseEntity.ok(stats);
    }

    /**
     * 处理反馈 (例如, 批准)
     *
     * @param id 反馈ID
     * @param request 包含新状态和备注的请求体
     * @return 更新后的反馈详情
     */
    @PostMapping("/{id}/process")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERVISOR')")
    @Operation(summary = "Process a feedback entry", description = "Processes a feedback, e.g., approving it to be pending assignment.")
    public ResponseEntity<FeedbackResponseDTO> processFeedback(
            @PathVariable Long id,
            @Valid @RequestBody ProcessFeedbackRequest request) {
        FeedbackResponseDTO updatedFeedback = feedbackService.processFeedback(id, request);
        return ResponseEntity.ok(updatedFeedback);
    }
}