package com.ssyf.module.auth.gauth;

import com.warrenstrange.googleauth.GoogleAuthenticator;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey;
import org.springframework.stereotype.Service;

@Service
public class TwoFactorAuthService {

    private final GoogleAuthenticator gAuth = new GoogleAuthenticator();

    /**
     * 1. 生成随机的 Secret Key
     */
    public String generateSecretKey() {
        final GoogleAuthenticatorKey key = gAuth.createCredentials();
        return key.getKey();
    }

    /**
     * 2. 生成二维码内容的 URL (otpauth://...)
     * 前端将把这个字符串转换为二维码图片
     */
    public String getQrCodeUrl(String secretKey, String accountName, String issuer) {
        // 格式: otpauth://totp/Issuer:AccountName?secret=...&issuer=...
        return String.format("otpauth://totp/%s:%s?secret=%s&issuer=%s",
                issuer, accountName, secretKey, issuer);
    }

    /**
     * 3. 验证用户输入的 6 位数字代码
     */
    public boolean validateCode(String secretKey, int code) {
        return gAuth.authorize(secretKey, code);
    }
}