package parser

import (
	"testing"
	"time"

	"git.mchus.pro/mchus/logpile/internal/models"
)

func TestAppendExtractionWarnings(t *testing.T) {
	result := &models.AnalysisResult{
		Events: make([]models.Event, 0),
	}

	files := []ExtractedFile{
		{Path: "ok.log", Content: []byte("ok")},
		{Path: "big.log", Truncated: true, TruncatedMessage: "file exceeded size limit and was truncated"},
	}

	appendExtractionWarnings(result, files)

	if len(result.Events) != 1 {
		t.Fatalf("expected 1 warning event, got %d", len(result.Events))
	}
	ev := result.Events[0]
	if ev.Severity != models.SeverityWarning {
		t.Fatalf("expected warning severity, got %q", ev.Severity)
	}
	if ev.EventType != "Analysis Warning" {
		t.Fatalf("unexpected event type: %q", ev.EventType)
	}
	if ev.RawData == "" {
		t.Fatalf("expected warning details in RawData")
	}
}

func TestInferCollectedAtFromExtractedFiles_PrefersReliableMTime(t *testing.T) {
	files := []ExtractedFile{
		{Path: "a.log", ModTime: time.Date(1980, 1, 1, 0, 0, 0, 0, time.UTC)},
		{Path: "b.log", ModTime: time.Date(2025, 12, 12, 10, 14, 49, 0, time.FixedZone("EST", -5*3600))},
		{Path: "c.log", ModTime: time.Date(2026, 2, 28, 4, 18, 18, 0, time.FixedZone("UTC+8", 8*3600))},
	}

	got := inferCollectedAtFromExtractedFiles(files)
	want := files[2].ModTime
	if !got.Equal(want) {
		t.Fatalf("expected %s, got %s", want, got)
	}
}

func TestInferCollectedAtFromExtractedFiles_FallsBackToAnyMTime(t *testing.T) {
	files := []ExtractedFile{
		{Path: "a.log", ModTime: time.Date(1980, 1, 1, 0, 0, 0, 0, time.UTC)},
		{Path: "b.log", ModTime: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC)},
	}

	got := inferCollectedAtFromExtractedFiles(files)
	want := files[0].ModTime
	if !got.Equal(want) {
		t.Fatalf("expected fallback %s, got %s", want, got)
	}
}
