// KEKS -- Go KEKS codec implementation
// Copyright (C) 2024-2025 Anton Rudenko <rudenko.ad@phystech.edu>
//                         Sergey Matveev <stargrave@stargrave.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program.  If not, see <http://www.gnu.org/licenses/>.

package keks

import (
	"bytes"
	"math/rand/v2"
	"strconv"
	"testing"
	"testing/quick"
)

func TestMapEmpty(t *testing.T) {
	bin := []byte("\x09\x00")
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(struct{}{}, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.(map[string]any)
	if !ok {
		t.Fatal("failed to cast")
	}
	if len(casted) != 0 {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestMapEncodeNonStrKey(t *testing.T) {
	_, err := EncodeBuf(map[any]any{123: 123}, nil)
	if err != ErrMapBadKey {
		t.Fatal(err)
	}
}

func TestMapDecodeNonStrKey(t *testing.T) {
	_, err := NewDecoderFromBytes([]byte("\x09\x0C\x80\xC6value2\x00"), nil).Decode()
	if err != ErrMapBadKey {
		t.Fatal(err)
	}
}

func TestMapUnexpectedEOC(t *testing.T) {
	_, err := NewDecoderFromBytes([]byte("\x09\xC4key1\x00\x00"), nil).Decode()
	if err != ErrEOCUnexpected {
		t.Fatal(err)
	}
}

func TestMapEncodeEmptyStrKey(t *testing.T) {
	_, err := EncodeBuf(map[string]any{"": 123}, nil)
	if err != ErrMapBadKey {
		t.Fatal(err)
	}
}

func TestMapDecodeEmptyStrKey(t *testing.T) {
	_, err := NewDecoderFromBytes(mustHexDec("09C0C000"), nil).Decode()
	if err != ErrMapBadKey {
		t.Fatal(err)
	}
}

func TestMapUnsortedValueKeys(t *testing.T) {
	bin := bytes.Join([][]byte{
		mustHexDec("09"),
		mustHexDec("C4"), []byte("key2"),
		mustHexDec("0C8101"),
		mustHexDec("C4"), []byte("key1"),
		mustHexDec("C6"), []byte("value1"),
		mustHexDec("00"),
	}, nil)
	_, err := NewDecoderFromBytes(bin, nil).Decode()
	if err != ErrMapUnordered {
		t.Fatal(err)
	}
}

func TestMapUnsortedLenKeys(t *testing.T) {
	bin := bytes.Join([][]byte{
		mustHexDec("09"),
		mustHexDec("C4"), []byte("key2"),
		mustHexDec("0C8101"),
		mustHexDec("C3"), []byte("key"),
		mustHexDec("C6"), []byte("value1"),
		mustHexDec("00"),
	}, nil)
	_, err := NewDecoderFromBytes(bin, nil).Decode()
	if err != ErrMapUnordered {
		t.Fatal(err)
	}
}

func TestMapMaxContLen(t *testing.T) {
	l := 2 + rand.UintN(8)
	m := make(map[string]int, l)
	for i := range l {
		m[strconv.Itoa(int(i))] = 123
	}
	bin, err := EncodeBuf(m, nil)
	if err != nil {
		t.Fatal(err)
	}
	decoder := NewDecoderFromBytes(bin, nil)
	_, err = decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	decoder = NewDecoderFromBytes(bin, &DecodeOpts{MaxContLen: int64(l) + 1})
	_, err = decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	decoder = NewDecoderFromBytes(bin, &DecodeOpts{MaxContLen: int64(l)})
	_, err = decoder.Decode()
	if err != ErrLenTooBig {
		t.Fatal(err)
	}
}

func TestMapIntSymmetric(t *testing.T) {
	f := func(m map[int]uint64) bool {
		obj := make(map[string]uint64, len(m))
		for k, v := range m {
			obj[strconv.Itoa(k)] = v
		}
		m = nil
		encoded, err := EncodeBuf(obj, nil)
		if err != nil {
			t.Fatal(err)
		}
		decoder := NewDecoderFromBytes(append(encoded, Junk...), nil)
		decoded, err := decoder.Decode()
		if err != nil {
			t.Fatal(err)
		}
		if !bytes.Equal(decoder.B, Junk) {
			t.Fatal("tail differs")
		}
		casted, ok := decoded.(map[string]any)
		if !ok {
			t.Fatal("failed to cast")
		}
		if len(casted) != len(obj) {
			return false
		}
		for k := range obj {
			v, ok := casted[k]
			if !ok {
				return false
			}
			i, ok := v.(uint64)
			if !ok {
				t.Fatal("failed to cast")
			}
			if i != obj[k] {
				return false
			}
		}
		return true
	}
	if err := quick.Check(f, nil); err != nil {
		t.Fatal(err)
	}
}

func TestMapTooDeep(t *testing.T) {
	k, err := EncodeBuf("k", nil)
	if err != nil {
		t.Fatal(err)
	}
	k = append([]byte{byte(AtomMap)}, k...)
	if _, err := NewDecoderFromBytes(
		bytes.Repeat(k, 1000), nil,
	).Decode(); err != ErrTooDeep {
		t.Fatal(err)
	}
}
