package com.usky.issue.controller.web;

import com.usky.common.core.bean.ApiResult;
import com.usky.issue.service.vo.TriggerEventResponse;
import com.usky.issue.service.vo.TriggerEventSaveRequest;
import com.usky.issue.service.CloudTriggerEventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 云平台触发事件接口
 *
 * @author fyc
 * @date 2026-05-21
 */
@Validated
@RestController
@RequestMapping("/cloud")
public class CloudTriggerEventController {

    @Autowired
    private CloudTriggerEventService cloudTriggerEventService;

    @GetMapping("/triggerEvents")
    public ApiResult<List<TriggerEventResponse>> listEvents() {
        return ApiResult.success(cloudTriggerEventService.listEvents());
    }

    @PutMapping("/triggerEvents")
    public ApiResult<Void> saveEvents(@Valid @RequestBody TriggerEventSaveRequest request,
                                      HttpServletRequest httpRequest) {
        cloudTriggerEventService.saveEvents(request, resolveOperator(httpRequest), httpRequest.getRemoteAddr());
        return ApiResult.success();
    }

    private String resolveOperator(HttpServletRequest request) {
        String user = request.getHeader("X-User-Name");
        return user != null ? user : "system";
    }
}
