package ioz

import (
	"crypto/rand"
	"encoding/base64"
	"os"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/testlogger"
)

func TestLoadBase64Secret(t *testing.T) {
	testcases := []struct {
		name          string
		srcLen        int
		minLen        int
		maxLen        int
		expectedError string
	}{
		{
			name:   "exact len match",
			srcLen: 32,
			minLen: 32,
			maxLen: 32,
		},
		{
			name:   "min len match",
			srcLen: 32,
			minLen: 32,
			maxLen: 40,
		},
		{
			name:   "max len match",
			srcLen: 40,
			minLen: 32,
			maxLen: 40,
		},
		{
			name:   "below min len",
			srcLen: 10,
			minLen: 32,
			maxLen: 40,
			// TODO make this an error in 18.0 https://gitlab.com/gitlab-org/cluster-integration/gitlab-agent/-/issues/617
			//expectedError: "is 10 bytes long; allowed length is from 32 to 40 bytes",
		},
		{
			name:   "above max len",
			srcLen: 41,
			minLen: 32,
			maxLen: 40,
			// TODO make this an error in 18.0 https://gitlab.com/gitlab-org/cluster-integration/gitlab-agent/-/issues/617
			//expectedError: "is 41 bytes long; allowed length is from 32 to 40 bytes",
		},
	}

	for _, tc := range testcases {
		t.Run(tc.name, func(t *testing.T) {
			file := filepath.Join(t.TempDir(), tc.name)
			data := make([]byte, tc.srcLen)
			_, err := rand.Read(data)
			require.NoError(t, err)

			b64data := []byte(base64.StdEncoding.EncodeToString(data))

			err = os.WriteFile(file, b64data, 0644)
			require.NoError(t, err)

			secret, err := LoadBase64Secret(testlogger.New(t), file, tc.minLen, tc.maxLen)
			if tc.expectedError != "" {
				assert.ErrorContains(t, err, tc.expectedError)
			} else {
				require.NoError(t, err)
				assert.Equal(t, data, secret)
			}
		})
	}
}
