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

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

func TestBlobMultipleOfChunkLen(t *testing.T) {
	bin := bytes.Join([][]byte{
		mustHexDec("0B0000000000000003"),
		{0x84},
		[]byte("test"),
		{0x84},
		[]byte("data"),
		{0x80},
	}, nil)
	data := []byte("test" + "data")
	encoded, err := EncodeBuf(BlobReader{
		ChunkLen: 4,
		R:        bytes.NewReader(data),
	}, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	decoder := NewDecoderFromBytes(append(encoded, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	casted, ok := decoded.(BlobChunked)
	if !ok {
		t.Fatal("failed to cast")
	}
	if casted.Len() != 2*4 {
		t.Fatal("Len() differs")
	}
	if casted.ChunkLen != 4 {
		t.Fatal("ChunkLen differs")
	}
	if len(casted.Chunks) != 2 {
		t.Fatal("len(Chunks) differs")
	}
	if casted.Chunks[0] != "test" {
		t.Fatal("Chunks[0] differs")
	}
	if casted.Chunks[1] != "data" {
		t.Fatal("Chunks[1] differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
	got, err := io.ReadAll(casted.Reader())
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(got, data) {
		t.Fatal("reader differs")
	}
}

func TestBlobLargerOfChunkLen(t *testing.T) {
	bin := bytes.Join([][]byte{
		mustHexDec("0B0000000000000003"),
		{0x84},
		[]byte("test"),
		{0x84},
		[]byte("data"),
		{0x81},
		[]byte("2"),
	}, nil)
	data := []byte("test" + "data" + "2")
	encoded, err := EncodeBuf(BlobReader{
		ChunkLen: 4,
		R:        bytes.NewReader(data),
	}, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	decoder := NewDecoderFromBytes(append(encoded, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	casted, ok := decoded.(BlobChunked)
	if !ok {
		t.Fatal("failed to cast")
	}
	if casted.Len() != 2*4+1 {
		t.Fatal("Len() differs")
	}
	if casted.ChunkLen != 4 {
		t.Fatal("ChunkLen differs")
	}
	if len(casted.Chunks) != 3 {
		t.Fatal("len(Chunks) differs")
	}
	if casted.Chunks[0] != "test" {
		t.Fatal("Chunks[0] differs")
	}
	if casted.Chunks[1] != "data" {
		t.Fatal("Chunks[1] differs")
	}
	if casted.Chunks[2] != "2" {
		t.Fatal("Chunks[2] differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
	got, err := io.ReadAll(casted.Reader())
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(got, data) {
		t.Fatal("reader differs")
	}
}

func TestBlobEmpty(t *testing.T) {
	bin := mustHexDec("0B0000000000000003" + "80")
	encoded, err := EncodeBuf(BlobReader{
		ChunkLen: 4,
		R:        bytes.NewReader(nil),
	}, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	decoder := NewDecoderFromBytes(append(encoded, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	casted, ok := decoded.(BlobChunked)
	if !ok {
		t.Fatal("failed to cast")
	}
	if casted.Len() != 0 {
		t.Fatal("Len() differs")
	}
	if casted.ChunkLen != 4 {
		t.Fatal("ChunkLen differs")
	}
	if len(casted.Chunks) != 0 {
		t.Fatal("len(Chunks) differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
	got, err := io.ReadAll(casted.Reader())
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(got, []byte{}) {
		t.Fatal("reader differs")
	}
}

func TestBlobSymmetric(t *testing.T) {
	var err error
	f := func(chunkLen, chunksN uint8) bool {
		if chunkLen == 0 {
			chunkLen++
		}
		chunks := make([][]byte, 0, chunksN)
		mr := make([]io.Reader, 0, chunksN)
		for range chunksN {
			chunk := make([]byte, chunkLen)
			if _, err = io.ReadFull(PRNG, chunk); err != nil {
				panic(err)
			}
			chunks = append(chunks, chunk)
			mr = append(mr, bytes.NewReader(chunk))
		}
		encoded, err := EncodeBuf(BlobReader{
			ChunkLen: int64(chunkLen),
			R:        io.MultiReader(mr...),
		}, 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.(BlobChunked)
		if !ok {
			t.Fatal("failed to cast")
		}
		if casted.Len() != int64(chunkLen)*int64(chunksN) {
			t.Fatal("Len() differs")
		}
		if casted.ChunkLen != int64(chunkLen) {
			t.Fatal("ChunkLen differs")
		}
		if len(casted.Chunks) != int(chunksN) {
			t.Fatal("len(Chunks) differs")
		}
		for i := range len(chunks) {
			if casted.Chunks[i] != string(chunks[i]) {
				t.Fatal("chunk differs")
			}
		}
		return true
	}
	if err := quick.Check(f, nil); err != nil {
		t.Fatal(err)
	}
}

func TestBlobNotEnoughData(t *testing.T) {
	bin := bytes.Join([][]byte{
		mustHexDec("0B0000000000000003"),
		{0x84},
		[]byte("test"),
		{0x84},
		[]byte("da"),
	}, nil)
	_, err := NewDecoderFromBytes(bin, nil).Decode()
	if err != io.ErrUnexpectedEOF {
		t.Fatal(err)
	}
}

func TestBlobTooLong(t *testing.T) {
	bin := make([]byte, 1+8)
	bin[0] = byte(AtomBLOB)
	be.Put(bin[1:], (1<<63)-1)
	_, err := NewDecoderFromBytes(bin, nil).Decode()
	if err != ErrLenTooBig {
		t.Fatal(err)
	}
}

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

func TestBlobWrongTerminatorLength(t *testing.T) {
	bin := bytes.Join([][]byte{
		mustHexDec("0B0000000000000003"),
		{0x84},
		[]byte("test"),
		{0x84},
		[]byte("data"),
		{0x8A},
		[]byte("terminator"),
	}, nil)
	_, err := NewDecoderFromBytes(bin, nil).Decode()
	if err != ErrBlobBadChunkLen {
		t.Fatal(err)
	}
}

func TestBlobWrongTerminatorTag(t *testing.T) {
	bin := bytes.Join([][]byte{
		mustHexDec("0B0000000000000003"),
		{0x84},
		[]byte("test"),
		{0x84},
		[]byte("data"),
		{0x04},
		[]byte("that was a wrong tag"),
	}, nil)
	_, err := NewDecoderFromBytes(bin, nil).Decode()
	if err != ErrBlobBadAtom {
		t.Fatal(err)
	}
}

func TestBlobTooDeep(t *testing.T) {
	bin := []byte{byte(AtomBLOB)}
	bin = append(bin, bytes.Repeat([]byte{0x01}, 8)...)
	bin = append(bin, bytes.Repeat([]byte{byte(AtomList)}, 1000)...)
	if _, err := NewDecoderFromBytes(bin, nil).Decode(); err != ErrBlobBadAtom {
		t.Fatal(err)
	}
}
