package com.sunyard.chsm.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sunyard.chsm.model.entity.KeyRecord;
import org.apache.ibatis.annotations.Mapper;

import java.time.LocalDateTime;

/**
 * @author liulu
 * @since 2024/10/22
 */
@Mapper
public interface SpKeyRecordMapper extends BaseMapper<KeyRecord> {

    default KeyRecord selectUsedByKeyId(Long id) {
        LocalDateTime now = LocalDateTime.now();
        return selectOne(
                new LambdaQueryWrapper<KeyRecord>()
                        .eq(KeyRecord::getKeyId, id)
                        .lt(KeyRecord::getEffectiveTime, now)
                        .gt(KeyRecord::getExpiredTime, now)
        );
    }

    default KeyRecord selectByPubKey(String pubKey) {
        if (pubKey == null || pubKey.length() != 128) {
            return null;
        }
        return selectOne(
                new LambdaQueryWrapper<KeyRecord>()
                        .eq(KeyRecord::getPubIdx, pubKey.substring(0, 8))
                        .eq(KeyRecord::getPubKey, pubKey)
        );
    }


}
