package com.sunyard.chsm.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sunyard.chsm.enums.KeyUsage;
import com.sunyard.chsm.model.Subject;
import com.sunyard.chsm.model.entity.AppCert;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author liulu
 * @since 2024/11/6
 */
@Mapper
public interface AppCertMapper extends BaseMapper<AppCert> {


    default AppCert selectBySN(String sn) {
        Assert.hasText(sn, "证书序列号不能为空");
        List<AppCert> certs = selectList(new LambdaQueryWrapper<AppCert>()
                .eq(AppCert::getSerialNumber, sn)
        );
        if (CollectionUtils.isEmpty(certs)) {
            return null;
        }
        return certs.iterator().next();
    }

    default AppCert selectSignBySubject(String dn) {
        Assert.hasText(dn, "证书序列号不能为空");
        String subject = Subject.fromDN(dn).getDN();
        List<AppCert> certs = selectList(new LambdaQueryWrapper<AppCert>()
                .eq(AppCert::getSubject, subject)
                .eq(AppCert::getCertType, KeyUsage.SIGN_VERIFY.getCode())
        );
        if (CollectionUtils.isEmpty(certs)) {
            return null;
        }
        return certs.iterator().next();
    }

    default AppCert selectByTypeAndDn(String type,String dn) {
        Assert.hasText(dn, "证书序列号不能为空");
        String subject = Subject.fromDN(dn).getDN();
        List<AppCert> certs = selectList(new LambdaQueryWrapper<AppCert>()
                .eq(AppCert::getSubject, subject)
                .eq(AppCert::getCertType, type)
        );
        if (CollectionUtils.isEmpty(certs)) {
            return null;
        }
        return certs.iterator().next();
    }


}
