package parser

import (
	"bytes"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestExtractArchiveFromReaderTXT(t *testing.T) {
	content := "loader_brand=\"XigmaNAS\"\nSystem uptime:\n"
	files, err := ExtractArchiveFromReader(strings.NewReader(content), "xigmanas.txt")
	if err != nil {
		t.Fatalf("extract txt from reader: %v", err)
	}
	if len(files) != 1 {
		t.Fatalf("expected 1 file, got %d", len(files))
	}
	if files[0].Path != "xigmanas.txt" {
		t.Fatalf("expected filename xigmanas.txt, got %q", files[0].Path)
	}
	if string(files[0].Content) != content {
		t.Fatalf("content mismatch")
	}
}

func TestExtractArchiveTXT(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "sample.txt")
	want := "plain text log"
	if err := os.WriteFile(path, []byte(want), 0o600); err != nil {
		t.Fatalf("write sample txt: %v", err)
	}

	files, err := ExtractArchive(path)
	if err != nil {
		t.Fatalf("extract txt file: %v", err)
	}
	if len(files) != 1 {
		t.Fatalf("expected 1 file, got %d", len(files))
	}
	if files[0].Path != "sample.txt" {
		t.Fatalf("expected sample.txt, got %q", files[0].Path)
	}
	if string(files[0].Content) != want {
		t.Fatalf("content mismatch")
	}
}

func TestExtractArchiveFromReaderTXT_TruncatedWhenTooLarge(t *testing.T) {
	large := bytes.Repeat([]byte("a"), maxSingleFileSize+1024)
	files, err := ExtractArchiveFromReader(bytes.NewReader(large), "huge.log")
	if err != nil {
		t.Fatalf("extract huge txt from reader: %v", err)
	}
	if len(files) != 1 {
		t.Fatalf("expected 1 file, got %d", len(files))
	}

	f := files[0]
	if !f.Truncated {
		t.Fatalf("expected file to be marked as truncated")
	}
	if got := len(f.Content); got != maxSingleFileSize {
		t.Fatalf("expected truncated size %d, got %d", maxSingleFileSize, got)
	}
	if f.TruncatedMessage == "" {
		t.Fatalf("expected truncation message")
	}
}
