package cmd

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	libshare "github.com/celestiaorg/go-square/v3/share"
)

func Test_parseNamespaceID(t *testing.T) {
	type testCase struct {
		name    string
		param   string
		want    []byte
		wantErr bool
	}
	testCases := []testCase{
		{
			param: "0x0c204d39600fddd3",
			name:  "8 byte hex encoded namespace ID gets left padded",
			want: []byte{
				0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
				0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc, 0x20, 0x4d, 0x39, 0x60, 0xf, 0xdd, 0xd3,
			},
			wantErr: false,
		},
		{
			name:  "10 byte hex encoded namespace ID",
			param: "0x42690c204d39600fddd3",
			want: []byte{
				0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
				0x0, 0x0, 0x0, 0x0, 0x42, 0x69, 0xc, 0x20, 0x4d, 0x39, 0x60, 0xf, 0xdd, 0xd3,
			},
			wantErr: false,
		},
		{
			name:  "29 byte hex encoded namespace ID",
			param: "0x0000000000000000000000000000000000000001010101010101010101",
			want: []byte{
				0x0,                                                                                      // namespace version
				0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // v0 ID prefix
				0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, // namespace ID
			},
			wantErr: true,
		},
		{
			name:    "11 byte hex encoded namespace ID returns error",
			param:   "0x42690c204d39600fddd3a3",
			want:    nil,
			wantErr: true,
		},
		{
			name:  "10 byte base64 encoded namespace ID",
			param: "QmkMIE05YA/d0w==",
			want: []byte{
				0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
				0x0, 0x0, 0x0, 0x0, 0x42, 0x69, 0xc, 0x20, 0x4d, 0x39, 0x60, 0xf, 0xdd, 0xd3,
			},
			wantErr: false,
		},
		{
			name:    "not base64 or hex encoded namespace ID returns error",
			param:   "5748493939429",
			want:    nil,
			wantErr: true,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			got, err := ParseV0Namespace(tc.param)
			if tc.wantErr {
				assert.Error(t, err)
				return
			}

			assert.NoError(t, err)
			ns, err := libshare.NewNamespaceFromBytes(tc.want)
			require.NoError(t, err)
			assert.Equal(t, ns, got)
		})
	}
}
