package erf

import (
	"bytes"
	"testing"
)

func TestArchiveRoundTrip(t *testing.T) {
	archive := New("MOD ", []Resource{
		{Name: "module", Type: 0x07DE, Data: []byte("ifo")},
		{Name: "start", Type: 0x07DC, Data: []byte("are")},
	})

	var buf bytes.Buffer
	if err := Write(&buf, archive); err != nil {
		t.Fatalf("write: %v", err)
	}

	decoded, err := Read(bytes.NewReader(buf.Bytes()))
	if err != nil {
		t.Fatalf("read: %v", err)
	}

	if len(decoded.Resources) != 2 {
		t.Fatalf("expected 2 resources, got %d", len(decoded.Resources))
	}
	if decoded.Resources[0].Name != "module" || string(decoded.Resources[0].Data) != "ifo" {
		t.Fatalf("unexpected first resource: %#v", decoded.Resources[0])
	}
}

func TestExtensionMappingsKeep2DAAndTLKDistinct(t *testing.T) {
	resourceType, ok := ResourceTypeForExtension("2da")
	if !ok {
		t.Fatal("expected 2da resource type")
	}
	if resourceType != 0x07E1 {
		t.Fatalf("expected 2da type 0x07E1, got 0x%04X", resourceType)
	}
	extension, ok := ExtensionForResourceType(resourceType)
	if !ok {
		t.Fatal("expected canonical extension for 2da type")
	}
	if extension != "2da" {
		t.Fatalf("expected 2da extension, got %q", extension)
	}

	tlkType, ok := ResourceTypeForExtension("tlk")
	if !ok {
		t.Fatal("expected tlk resource type")
	}
	if tlkType != 0x07E2 {
		t.Fatalf("expected tlk type 0x07E2, got 0x%04X", tlkType)
	}
	if tlkType == resourceType {
		t.Fatal("expected 2da and tlk resource types to stay distinct")
	}
}

func TestHAKResourceTypeForExtensionSupportsPNG(t *testing.T) {
	if resourceType, ok := HAKResourceTypeForExtension("png"); !ok || resourceType != 0x083E {
		t.Fatalf("expected png to stay valid for HAK generation, got ok=%v type=0x%04X", ok, resourceType)
	}
	if resourceType, ok := HAKResourceTypeForExtension("2da"); !ok || resourceType != 0x07E1 {
		t.Fatalf("expected 2da to stay valid for HAK generation, got ok=%v type=0x%04X", ok, resourceType)
	}
}

func TestExtensionMappingsSupportModernAssetTypes(t *testing.T) {
	cases := map[string]uint16{
		"mtr": 0x0818,
		"shd": 0x0815,
		"txi": 0x07E6,
		"jpg": 0x081C,
		"mdb": 0x0816,
		"lyt": 0x0BB8,
		"vis": 0x0BB9,
		"mdx": 0x0BC0,
		"xml": 0x0BCD,
		"wlk": 0x0BCC,
		"gr2": 0x0FA3,
	}
	for ext, wantType := range cases {
		gotType, ok := ResourceTypeForExtension(ext)
		if !ok {
			t.Fatalf("expected %s to resolve to a resource type", ext)
		}
		if gotType != wantType {
			t.Fatalf("expected %s type 0x%04X, got 0x%04X", ext, wantType, gotType)
		}
		gotExt, ok := ExtensionForResourceType(wantType)
		if !ok {
			t.Fatalf("expected type 0x%04X to resolve back to an extension", wantType)
		}
		if gotExt != ext {
			t.Fatalf("expected type 0x%04X to resolve to %s, got %s", wantType, ext, gotExt)
		}
	}
}
