package com.yimeng.okr.controller;

import com.yimeng.okr.dto.ApiResult;
import com.yimeng.okr.annotation.OperationLogAnnotation;
import com.yimeng.okr.dto.PeriodReadinessDto;
import com.yimeng.okr.entity.AssessmentPeriod;
import com.yimeng.okr.entity.PeriodParticipant;
import com.yimeng.okr.enums.PeriodStatus;
import com.yimeng.okr.enums.UserRole;
import com.yimeng.okr.exception.BusinessException;
import com.yimeng.okr.security.SecurityUtils;
import com.yimeng.okr.service.AssessmentPeriodService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/periods")
@RequiredArgsConstructor
public class AssessmentPeriodController {

    private final AssessmentPeriodService periodService;

    @GetMapping
    public ApiResult<List<AssessmentPeriod>> list() {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean isAdmin = SecurityUtils.isCurrentUserAdmin();
        return ApiResult.success(periodService.list(isAdmin));
    }

    @GetMapping("/{id}")
    public ApiResult<AssessmentPeriod> getById(@PathVariable Long id) {
        return ApiResult.success(periodService.getById(id));
    }

    @GetMapping("/{id}/readiness")
    public ApiResult<PeriodReadinessDto> checkReadiness(@PathVariable Long id, @RequestParam String target) {
        return ApiResult.success(periodService.checkReadiness(id, PeriodStatus.valueOf(target)));
    }

    @GetMapping("/active")
    public ApiResult<AssessmentPeriod> getActive() {
        return ApiResult.success(periodService.getActivePeriod());
    }

    @PostMapping
    @OperationLogAnnotation(action = "CREATE_PERIOD", entityType = "assessment_period")
    public ApiResult<AssessmentPeriod> create(@RequestBody AssessmentPeriod period) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        return ApiResult.success(periodService.create(period));
    }

    @PutMapping("/{id}")
    @OperationLogAnnotation(action = "UPDATE_PERIOD", entityType = "assessment_period")
    public ApiResult<Void> update(@PathVariable Long id, @RequestBody AssessmentPeriod period) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        period.setId(id);
        periodService.update(period);
        return ApiResult.success();
    }

    @DeleteMapping("/{id}")
    @OperationLogAnnotation(action = "DELETE_PERIOD", entityType = "assessment_period")
    public ApiResult<Void> delete(@PathVariable Long id) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        periodService.delete(id);
        return ApiResult.success();
    }

    @PutMapping("/{id}/status")
    @OperationLogAnnotation(action = "TRANSITION_PERIOD", entityType = "assessment_period")
    public ApiResult<Void> transitionStatus(@PathVariable Long id, @RequestBody Map<String, String> body) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        PeriodStatus target = PeriodStatus.valueOf(body.get("status"));
        periodService.transitionStatus(id, target);
        return ApiResult.success();
    }

    @PostMapping("/batch")
    @OperationLogAnnotation(action = "BATCH_CREATE_PERIOD", entityType = "assessment_period")
    public ApiResult<List<AssessmentPeriod>> batchCreate(@RequestBody Map<String, Object> body) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        return ApiResult.success(periodService.batchCreate(body));
    }

    @PostMapping("/{id}/participants/{userId}/exempt")
    @OperationLogAnnotation(action = "EXEMPT_PERIOD_PARTICIPANT", entityType = "period_participant")
    public ApiResult<PeriodParticipant> exemptParticipant(@PathVariable Long id,
                                                          @PathVariable Long userId,
                                                          @RequestBody Map<String, Object> body) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        String reason = body.getOrDefault("reason", "").toString();
        return ApiResult.success(periodService.exemptParticipant(id, userId, SecurityUtils.getCurrentUserId(), reason));
    }

    @GetMapping("/{id}/participants")
    public ApiResult<List<PeriodParticipant>> listParticipants(@PathVariable Long id) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        return ApiResult.success(periodService.listParticipants(id));
    }

    @PostMapping("/{id}/participants/{userId}")
    @OperationLogAnnotation(action = "ADD_PERIOD_PARTICIPANT", entityType = "period_participant")
    public ApiResult<PeriodParticipant> addParticipant(@PathVariable Long id, @PathVariable Long userId) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        return ApiResult.success(periodService.addParticipant(id, userId));
    }

    @PutMapping("/{id}/participants/{userId}/activate")
    @OperationLogAnnotation(action = "ACTIVATE_PERIOD_PARTICIPANT", entityType = "period_participant")
    public ApiResult<PeriodParticipant> activateParticipant(@PathVariable Long id, @PathVariable Long userId) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        return ApiResult.success(periodService.activateParticipant(id, userId));
    }
}
