package cn.sikey.hmd.api;

import cn.sikey.framework.common.exception.ServiceException;
import cn.sikey.framework.common.pojo.CommonResult;
import cn.sikey.hmd.api.hmd.DeviceActivationApi;
import cn.sikey.hmd.api.hmd.dto.activation.DeviceActivationDTO;
import cn.sikey.hmd.api.hmd.vo.activation.UpdateRemainingTimesExpireTimeReqVO;
import cn.sikey.hmd.enums.ValidityEnum;
import cn.sikey.hmd.service.activation.DeviceActivationService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 设备激活 API 接口实现类
 *
 * @author qin
 */
@Slf4j
@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class DeviceActivationApiImpl implements DeviceActivationApi {

    @Resource
    private DeviceActivationService deviceActivationService;

    @Override
    public CommonResult<Void> updateRemainingTimesExpireTime(@RequestBody @Validated UpdateRemainingTimesExpireTimeReqVO updateRemainingTimesExpireTimeReqVO) {
        String deviceId = updateRemainingTimesExpireTimeReqVO.getDeviceId();

        DeviceActivationDTO queryDeviceActivation = deviceActivationService.queryDeviceActivation(deviceId);
        if (Objects.isNull(queryDeviceActivation)) {
            log.warn("[设备激活]不存在设备激活数据，设备编码：{}", deviceId);
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "不存在设备激活数据");
        }

        deviceActivationService.updateDeviceActivation(deviceId, queryDeviceActivation.getFreeExpireTime(),
                queryDeviceActivation.getFinalExpireTime(),
                LocalDateTime.now(), ValidityEnum.YEAR.getValue());
        return CommonResult.success();
    }

    @Override
    public CommonResult<DeviceActivationDTO> queryDeviceActivation(String deviceId) {
        return CommonResult.success(deviceActivationService.queryDeviceActivation(deviceId));
    }
}
