package auth

import (
	"encoding/base64"
	"testing"
	"time"

	"github.com/pquerna/otp"
	"github.com/pquerna/otp/totp"
)

func TestOTP(t *testing.T) {
	key, err := totp.Generate(totp.GenerateOpts{

		Issuer:      "System",
		AccountName: "Opsflow",
	})
	if err != nil {
		t.Error(err)
	}
	t.Log(key.Secret())
}

// OA5BDGLJ2DYGAWNCLJYSNZFAESPQ7BRL

func verify(sec, input string) bool {
	return totp.Validate(input, sec)
}

func TestAuth(t *testing.T) {
	sec := "OA5BDGLJ2DYGAWNCLJYSNZFAESPQ7BRL"
	out, err := totp.GenerateCode(sec, time.Now())
	if err != nil {
		t.Error(err)
	}
	t.Log(out)

	if verify(sec, out) {
		t.Log("auth ok")
	} else {
		t.Log("auth fail")
	}

	ok, err := totp.ValidateCustom(out, sec, time.Now(), totp.ValidateOpts{
		Period:    30, // 每 30 秒更新一次
		Skew:      1,  // 允许前后偏移 1 个周期（即允许 30 秒的时间误差）
		Digits:    otp.DigitsSix,
		Algorithm: otp.AlgorithmSHA1,
	})
	if err != nil {
		t.Error(err)
	}
	t.Logf("auth result: %v\n", ok)
}

func TestGetCode(t *testing.T) {
	sec := "OA5BDGLJ2DYGAWNCLJYSNZFAESPQ7BRL"
	out, err := totp.GenerateCode(sec, time.Now())
	if err != nil {
		t.Error(err)
	}
	t.Log(base64.StdEncoding.EncodeToString([]byte(out)))
}
