package api;

import com.sunyard.chsm.enums.KeyAlg;
import com.sunyard.chsm.enums.KeyStatus;
import com.sunyard.chsm.model.entity.KeyInfo;
import com.sunyard.chsm.param.KeyCreateReq;
import com.sunyard.chsm.param.KeyManageReq;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.time.LocalDateTime;
import java.util.Collections;

/**
 * @author liulu
 * @since 2024/12/17
 */
@Slf4j
public class KeyManageTest extends BaseTest {


    @Test
    public void keyLifeTest() {
        Long sm4KeyId = execute("/key/gen", KeyCreateReq.builder().keyTemplateCode(keyTemplate).genNumber(1).build(), Long.class);
        Assertions.assertTrue(sm4KeyId != null &&sm4KeyId > 0);

        //
        KeyInfo keyInfo = execute("/key/info", sm4KeyId, KeyInfo.class);
        Assertions.assertNotNull(keyInfo);
        Assertions.assertEquals(KeyAlg.SM4.getCode(), keyInfo.getKeyAlg());
        Assertions.assertEquals(KeyStatus.ENABLED.getCode(), keyInfo.getStatus());
        LocalDateTime now = LocalDateTime.now();
        Assertions.assertTrue(now.isAfter(keyInfo.getEffectiveTime()) && now.isBefore(keyInfo.getExpiredTime()));

        //
        KeyManageReq keyManageReq = new KeyManageReq();
        keyManageReq.setIds(Collections.singletonList(sm4KeyId));

        execute("/key/disable", keyManageReq, Void.class);
        keyInfo = execute("/key/info", sm4KeyId, KeyInfo.class);
        Assertions.assertNotNull(keyInfo);
        Assertions.assertEquals(KeyStatus.DISABLED.getCode(), keyInfo.getStatus());

        //
        execute("/key/enable", keyManageReq, Void.class);
        keyInfo = execute("/key/info", sm4KeyId, KeyInfo.class);
        Assertions.assertNotNull(keyInfo);
        Assertions.assertEquals(KeyStatus.ENABLED.getCode(), keyInfo.getStatus());
        execute("/key/disable", keyManageReq, Void.class);
        keyInfo = execute("/key/info", sm4KeyId, KeyInfo.class);
        Assertions.assertNotNull(keyInfo);
        Assertions.assertEquals(KeyStatus.DISABLED.getCode(), keyInfo.getStatus());

        execute("/key/archive", keyManageReq, Void.class);
        keyInfo = execute("/key/info", sm4KeyId, KeyInfo.class);
        Assertions.assertNotNull(keyInfo);
        Assertions.assertEquals(KeyStatus.ARCHIVED.getCode(), keyInfo.getStatus());


        execute("/key/destroy", keyManageReq, Void.class);
        keyInfo = execute("/key/info", sm4KeyId, KeyInfo.class);
        Assertions.assertNull(keyInfo);
    }


}
