package com.bsmlab.dfx.agent.config;

import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

@Endpoint(id = "dfxagentShutdown")
@Component
@RequiredArgsConstructor
@Slf4j
public class DfxAgentShutdownEndpoint {
    private final ApplicationContext applicationContext;

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    public static class DfxAgentShutdownRequestDto {
        private String comment;
        private int exitCode;
        private int delaySeconds;
        private int forceAfterSeconds;
    }

    /**
     * # 지연 3초 후 종료, 15초 후 강제 종료(백업), exitCode=0
     * curl -X POST "http://localhost:63801/actuator/dfxagentShutdown" -H "Content-Type: application/json" -H "User-Agent: DFXConsole" -d "{\"comment\":\"배포하기 위해 종료\",\"exitCode\":0,\"delaySeconds\":3,\"forceAfterSeconds\":15}"
     * @param comment 예) "배포하기 위해 종료"
     * @param exitCode 0은 정상 종료 9는 강제 종료
     * @param delaySeconds 종료 실행 전 기다리는 시간(초)
     * @param forceAfterSeconds 강제 종료 전 기다리는 시간(초)
     * @return {@return }
     */
    @WriteOperation // Actuator 엔드포인트는 @WriteOperation 으로 POST 요청을 수신함. @ReadOperation GET 요청 수신
    public Map<String, Object> shutdown(String comment, int exitCode, int delaySeconds, int forceAfterSeconds) {
        Map<String, Object> receivedData = Map.of(
                "status", "SHUTDOWN_SCHEDULED",
                "comment", comment,
                "exitCode", exitCode,
                "delaySeconds", delaySeconds,
                "forceAfterSeconds", forceAfterSeconds
        );
        log.debug("{}", receivedData);
        return receivedData;
    }
}
