using Sdt.Core;
using Xunit;

namespace DevTool.Tests;

public sealed class RunEventLogReaderTests
{
    [Fact]
    public void ReadEvents_ParsesValidJsonlLines()
    {
        var root = Path.Combine(Path.GetTempPath(), "sdt-logreader-" + Guid.NewGuid().ToString("N"));
        var dir = Path.Combine(root, ".sdt", "events");
        Directory.CreateDirectory(dir);
        var file = Path.Combine(dir, "workflow-test.jsonl");
        File.WriteAllLines(file,
        [
            """{"category":"workflow","type":"WorkflowStarted","message":"start","workflowId":"build","occurredAt":"2026-03-01T10:00:00Z"}""",
            """{"category":"workflow","type":"WorkflowCompleted","message":"done","workflowId":"build","success":true,"exitCode":0,"occurredAt":"2026-03-01T10:00:01Z"}"""
        ]);

        var reader = new RunEventLogReader();
        var events = reader.ReadEvents(file);

        Assert.Equal(2, events.Count);
        Assert.Equal(RunEventType.WorkflowStarted, events[0].Type);
        Assert.Equal(RunEventType.WorkflowCompleted, events[1].Type);
        Assert.True(events[1].Success);
    }

    [Fact]
    public void ListEventFiles_ReturnsNewestFirst()
    {
        var root = Path.Combine(Path.GetTempPath(), "sdt-logreader-" + Guid.NewGuid().ToString("N"));
        var dir = Path.Combine(root, ".sdt", "events");
        Directory.CreateDirectory(dir);
        var older = Path.Combine(dir, "older.jsonl");
        var newer = Path.Combine(dir, "newer.jsonl");
        File.WriteAllText(older, "{}");
        Thread.Sleep(20);
        File.WriteAllText(newer, "{}");

        var reader = new RunEventLogReader();
        var files = reader.ListEventFiles(root);

        Assert.True(files.Count >= 2);
        Assert.Equal("newer.jsonl", files[0].Name);
    }
}
