package com.izouma.nineth.service.sms;

import com.izouma.nineth.config.Constants;
import com.izouma.nineth.exception.BusinessException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import java.util.Date;
import java.util.function.Supplier;

public interface SmsService {
    String sendVerify(String phone);

    String verify(String phone, String code);

    default String verifyToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(Constants.SMS_TOKEN_SECRET)
                    .parseClaimsJws(token)
                    .getBody();
            if (claims.getExpiration().before(new Date())) {
                throw new BusinessException("验证码已过期");
            }
            return claims.getSubject();
        } catch (Exception e) {
            throw new BusinessException("验证码无效");
        }
    }

    class SmsVerifyException extends Exception implements Supplier<SmsVerifyException> {
        public SmsVerifyException(String msg) {
            super(msg);
        }

        @Override
        public SmsVerifyException get() {
            return this;
        }
    }
}
