// KEKS -- Go KEKS codec implementation
// Copyright (C) 2024-2025 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"
)

func TestMagicSymmetric(t *testing.T) {
	f := func(m [12]byte) bool {
		encoded, err := EncodeBuf(Magic(m[:]), nil)
		if err != nil {
			t.Fatal(err)
		}
		decoder := NewDecoderFromBytes(append(encoded, Junk...), nil)
		decoded, err := decoder.Decode()
		if err != nil {
			t.Fatal(err)
		}
		casted, ok := decoded.(Magic)
		if !ok {
			t.Fatal("failed to cast")
		}
		if !bytes.Equal(decoder.B, Junk) {
			t.Fatal("tail differs")
		}
		return string(casted) == strings.TrimRight(string(m[:]), "\x00")
	}
	if err := quick.Check(f, nil); err != nil {
		t.Fatal(err)
	}
}

func TestMagicNotEnoughData(t *testing.T) {
	encoded, err := EncodeBuf(Magic("something"), nil)
	if err != nil {
		t.Fatal(err)
	}
	decoder := NewDecoderFromBytes(encoded[:len(encoded)-1], nil)
	_, err = decoder.Decode()
	if err != io.ErrUnexpectedEOF {
		t.Fatal(err)
	}
}

func TestMagicBadMagic(t *testing.T) {
	encoded, err := EncodeBuf(Magic("something"), nil)
	if err != nil {
		t.Fatal(err)
	}
	encoded[2] = 'e'
	decoder := NewDecoderFromBytes(encoded, nil)
	_, err = decoder.Decode()
	if err != ErrMagicBad {
		t.Fatal(err)
	}
}

func TestMagicVector(t *testing.T) {
	encoded, err := EncodeBuf(Magic("test-vector"), nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, []byte("KEKStest-vector\x00")) {
		t.Fail()
	}
}

func TestMagicEmpty(t *testing.T) {
	encoded, err := EncodeBuf(Magic(""), nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, append([]byte("KEKS"), bytes.Repeat([]byte{0}, 12)...)) {
		t.Fail()
	}
}
