package com.dne.ems.controller;

import java.util.List;

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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dne.ems.model.Assignment;
import com.dne.ems.model.Feedback;
import com.dne.ems.model.UserAccount;
import com.dne.ems.security.CustomUserDetails;
import com.dne.ems.service.TaskAssignmentService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 任务分配控制器，处理网格任务分配相关功能
 *
 * <p>主要职责：
 * <ul>
 *   <li>获取未分配任务列表</li>
 *   <li>查询可用网格工作人员</li>
 *   <li>分配任务给工作人员</li>
 * </ul>
 *
 * @author DNE开发团队
 * @version 1.0
 * @since 2024
 */
@RestController
@RequestMapping("/api/tasks")
@RequiredArgsConstructor
@Slf4j
public class TaskAssignmentController {

    private final TaskAssignmentService taskAssignmentService;

    /**
     * 获取未分配的任务列表
     *
     * @return 未分配的反馈任务列表
     * @throws AccessDeniedException 如果用户无权限
     */
    @GetMapping("/unassigned")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERVISOR')")
    public ResponseEntity<List<Feedback>> getUnassignedFeedback() {
        List<Feedback> feedbackList = taskAssignmentService.getUnassignedFeedback();
        return ResponseEntity.ok(feedbackList);
    }

    /**
     * 获取可用的网格工作人员列表
     *
     * @return 可用工作人员列表
     * @throws AccessDeniedException 如果用户无权限
     */
    @GetMapping("/grid-workers")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERVISOR')")
    public ResponseEntity<List<UserAccount>> getAvailableGridWorkers() {
        log.info("API接收到获取可用网格员列表的请求");
        try {
            List<UserAccount> workers = taskAssignmentService.getAvailableGridWorkers();
            log.info("成功获取到 {} 名可用的网格员", workers.size());
            return ResponseEntity.ok(workers);
        } catch (Exception e) {
            log.error("获取可用网格员列表时发生未知异常", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 分配任务给工作人员
     *
     * @param request 包含任务ID和分配人ID的请求体
     * @param adminDetails 当前管理员认证信息
     * @return 创建的任务分配记录
     * @throws ResourceNotFoundException 如果任务或工作人员不存在
     * @throws InvalidOperationException 如果任务已分配
     * @throws AccessDeniedException 如果用户无权限
     */
    @PostMapping("/assign")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERVISOR')")
    public ResponseEntity<Assignment> assignTask(
            @RequestBody AssignmentRequest request,
            @AuthenticationPrincipal CustomUserDetails adminDetails) {

        Long assignerId = adminDetails.getId();
        Assignment newAssignment = taskAssignmentService.assignTask(
                request.feedbackId(),
                request.assigneeId(),
                assignerId
        );
        return ResponseEntity.ok(newAssignment);
    }

    // A simple record to represent the assignment request payload
    public record AssignmentRequest(Long feedbackId, Long assigneeId) {}
} 