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

	"github.com/google/uuid"
)

func TestUUIDEncodeDecode(t *testing.T) {
	obj := uuid.MustParse("12345678-1234-5678-1234-567812345678")
	bin := mustHexDec("0412345678123456781234567812345678")
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	casted, ok := decoded.(*Hexlet)
	if !ok {
		t.Fatal("failed to cast")
	}
	if casted.UUID() != obj {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
}

func TestUUIDNotEnoughData(t *testing.T) {
	bin := mustHexDec("0412345678123456781234567812345678")
	_, err := NewDecoderFromBytes(bin[:len(bin)-4], nil).Decode()
	if err != io.ErrUnexpectedEOF {
		t.Fatal(err)
	}
}

func TestUUIDSymmetric(t *testing.T) {
	f := func(obj uuid.UUID) bool {
		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)
		}
		casted, ok := decoded.(*Hexlet)
		if !ok {
			t.Fatal("failed to cast")
		}
		if !bytes.Equal(decoder.B, Junk) {
			t.Fatal("tail differs")
		}
		return casted.UUID() == obj
	}
	if err := quick.Check(f, nil); err != nil {
		t.Fatal(err)
	}
}

func TestIPSymmetric(t *testing.T) {
	f := func(raw [16]byte) bool {
		obj := net.IP(raw[:])
		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)
		}
		casted, ok := decoded.(*Hexlet)
		if !ok {
			t.Fatal("failed to cast")
		}
		if !bytes.Equal(decoder.B, Junk) {
			t.Fatal("tail differs")
		}
		return casted.IP().Equal(obj)
	}
	if err := quick.Check(f, nil); err != nil {
		t.Fatal(err)
	}
}
