package system

import (
	"context"
	"errors"
	"kra/internal/biz/system"
	"os"
	"path/filepath"
	"testing"

	"kra/internal/conf"
)

func TestLogViewerReadsNestedCategoryFiles(t *testing.T) {
	root := t.TempDir()
	date := "2026-08-16"
	path := filepath.Join(root, date, "http", "access.log")
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(path, []byte("first\nsecond\n"), 0o644); err != nil {
		t.Fatal(err)
	}

	runtime := conf.NewRuntime(nil, &conf.AdminBackend{Zap: &conf.AdminBackend_Zap{Director: root}})
	repo := &logFileRepo{data: &Data{runtime: runtime}}
	files, err := repo.LogFiles(context.Background(), date)
	if err != nil {
		t.Fatal(err)
	}
	if len(files) != 1 || files[0].Path != "http/access.log" {
		t.Fatalf("unexpected nested log files: %+v", files)
	}
	content, err := repo.LogContent(context.Background(), date, "http/access.log", nil)
	if err != nil {
		t.Fatal(err)
	}
	if content.Content != "first\nsecond\n" || content.LineCount != 2 || content.HasMore {
		t.Fatalf("unexpected log content: %+v", content)
	}
}

func TestLogViewerRejectsPathTraversal(t *testing.T) {
	runtime := conf.NewRuntime(nil, &conf.AdminBackend{Zap: &conf.AdminBackend_Zap{Director: t.TempDir()}})
	repo := &logFileRepo{data: &Data{runtime: runtime}}
	_, err := repo.LogContent(context.Background(), "2026-08-16", "../application.log", nil)
	if !errors.Is(err, system.ErrInvalidLogPath) {
		t.Fatalf("expected invalid path error, got %v", err)
	}
}
