package authidentity

import (
	"encoding/base64"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/internal/core/secrets"
)

func TestMobileVerificationCodeHashMatchesCode(t *testing.T) {
	t.Parallel()

	hash, err := HashMobileVerificationCode("246810")
	require.NoError(t, err)
	require.Contains(t, hash, "$agentteam-mobile-otp$v=1$")

	matched, err := MobileVerificationCodeMatchesHash("246810", hash)
	require.NoError(t, err)
	require.True(t, matched)

	matched, err = MobileVerificationCodeMatchesHash("000000", hash)
	require.NoError(t, err)
	require.False(t, matched)
}

func TestMobileVerificationCodeMatchesLegacySHA256Hash(t *testing.T) {
	t.Parallel()

	matched, err := MobileVerificationCodeMatchesHash("246810", secrets.HashToken("246810"))
	require.NoError(t, err)
	require.True(t, matched)
}

func TestMobileVerificationCodeRejectsMalformedCurrentHashes(t *testing.T) {
	t.Parallel()

	salt := base64.RawStdEncoding.EncodeToString([]byte("1234567890abcdef"))
	hash := base64.RawStdEncoding.EncodeToString(make([]byte, mobileVerificationHashLength))
	for _, encoded := range []string{
		"$agentteam-mobile-otp$v=1$m=0,t=1,p=1$" + salt + "$" + hash,
		"$agentteam-mobile-otp$v=1$m=8192,t=0,p=1$" + salt + "$" + hash,
		"$agentteam-mobile-otp$v=1$m=8192,t=1,p=0$" + salt + "$" + hash,
		"$agentteam-mobile-otp$v=1$m=8192,t=1,p=1$short$" + hash,
		"$agentteam-mobile-otp$v=1$m=8192,t=1,p=1$" + salt + "$short",
	} {
		matched, err := MobileVerificationCodeMatchesHash("246810", encoded)
		require.Error(t, err, encoded)
		require.False(t, matched, encoded)
	}
}
