// 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"
	"io"
	"strings"
	"testing"
	"testing/quick"

	"go.cypherpunks.su/keks/be"
)

func TestBinEmpty(t *testing.T) {
	obj := []byte{}
	bin := mustHexDec("80")
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.([]byte)
	if !ok {
		t.Fatal("failed to cast")
	}
	if !bytes.Equal(casted, obj) {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestBin1234(t *testing.T) {
	obj := []byte{0x01, 0x02, 0x03, 0x04}
	bin := mustHexDec("8401020304")
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.([]byte)
	if !ok {
		t.Fatal("failed to cast")
	}
	if !bytes.Equal(casted, obj) {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestBinLen62(t *testing.T) {
	obj := bytes.Repeat([]byte{'a'}, 62)
	bin := mustHexDec("BD01" + strings.Repeat("61", 62))
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.([]byte)
	if !ok {
		t.Fatal("failed to cast")
	}
	if !bytes.Equal(casted, obj) {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestBinLen318(t *testing.T) {
	obj := bytes.Repeat([]byte{'a'}, 62+255+1)
	bin := mustHexDec("BE0001" + strings.Repeat("61", 62+255+1))
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.([]byte)
	if !ok {
		t.Fatal("failed to cast")
	}
	if !bytes.Equal(casted, obj) {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestBinLen65853(t *testing.T) {
	obj := bytes.Repeat([]byte{'a'}, 62+255+65535+1)
	bin := mustHexDec("BF0000000000000000" + strings.Repeat("61", 62+255+65535+1))
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.([]byte)
	if !ok {
		t.Fatal("failed to cast")
	}
	if !bytes.Equal(casted, obj) {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestBinNotEnoughData(t *testing.T) {
	bin := mustHexDec("84010203")
	_, err := NewDecoderFromBytes(bin, nil).Decode()
	if err != io.ErrUnexpectedEOF {
		t.Fatal()
	}
}

func TestBinNotEnoughDataForLength8(t *testing.T) {
	bin := mustHexDec("BD01" + strings.Repeat("61", 61))
	_, err := NewDecoderFromBytes(bin, nil).Decode()
	if err != io.ErrUnexpectedEOF {
		t.Fatal()
	}
}

func TestBinNotEnoughDataForLength16(t *testing.T) {
	bin := mustHexDec("BE0001" + strings.Repeat("61", 317))
	_, err := NewDecoderFromBytes(bin, nil).Decode()
	if err != io.ErrUnexpectedEOF {
		t.Fatal()
	}
}

func TestBinNotEnoughDataForLength64(t *testing.T) {
	bin := mustHexDec("BF0000000000000000" + strings.Repeat("61", 65852))
	_, err := NewDecoderFromBytes(bin, nil).Decode()
	if err != io.ErrUnexpectedEOF {
		t.Fatal()
	}
}

func TestBinTooLong(t *testing.T) {
	bin := make([]byte, 9)
	bin[0] = 0xBF
	for _, l := range []uint64{
		1 << 63,
		(1 << 63) - 63,
		(1 << 63) - 63 - ((1 << 8) - 1),
		(1 << 63) - 63 - ((1 << 8) - 1) - ((1 << 16) - 1) + 1,
	} {
		be.Put(bin[1:], l)
		decoder := NewDecoderFromBytes(bin, nil)
		_, err := decoder.Decode()
		if err != ErrLenTooBig {
			t.Fatal(err)
		}
	}
}

func TestBinNotTooLong(t *testing.T) {
	bin := make([]byte, 9)
	bin[0] = 0xBF
	be.Put(bin[1:], (1<<63)-63-((1<<8)-1)-((1<<16)-1))
	decoder := NewDecoderFromReader(bytes.NewReader(bin), nil)
	defer func() { recover() }()
	_, err := decoder.Decode()
	// it won't reach that code because it can not allocate so much
	// memory in .getBytes(), but that means, that no error was returned
	t.Fatal(err)
}

func TestBinMaxStrLen(t *testing.T) {
	f := func(bin []byte) bool {
		if len(bin) == 0 {
			return true
		}
		encoded, err := EncodeBuf(bin, nil)
		if err != nil {
			panic(err)
		}
		decoder := NewDecoderFromBytes(encoded,
			&DecodeOpts{MaxStrLen: int64(len(bin) + 1)})
		_, err = decoder.Decode()
		if err != nil {
			return false
		}
		decoder = NewDecoderFromBytes(encoded,
			&DecodeOpts{MaxStrLen: int64(len(bin))})
		_, err = decoder.Decode()
		if err != nil {
			return false
		}
		if len(bin) == 1 {
			return true
		}
		decoder = NewDecoderFromBytes(encoded,
			&DecodeOpts{MaxStrLen: int64(len(bin) - 1)})
		_, err = decoder.Decode()
		return err != nil
	}
	if err := quick.Check(f, nil); err != nil {
		t.Fatal(err)
	}
}

func TestBinSymmetric(t *testing.T) {
	f := func(bin []byte) bool {
		encoded, err := EncodeBuf(bin, nil)
		if err != nil {
			panic(err)
		}
		decoder := NewDecoderFromBytes(append(encoded, Junk...), nil)
		decoded, err := decoder.Decode()
		if err != nil {
			return false
		}
		casted, ok := decoded.([]byte)
		if !ok {
			return false
		}
		return bytes.Equal(bin, casted)
	}
	if err := quick.Check(f, nil); err != nil {
		t.Fatal(err)
	}
}
