using Microsoft.Extensions.Logging;
using Moq;
using QuantEngine.Application.Services;

namespace QuantEngine.Core.Tests;

public class CollectionBootstrapHostedServiceTests
{
    [Fact]
    public async Task StartAsync_WritesBootstrapArtifact()
    {
        var root = FindRepoRoot();
        var artifact = Path.Combine(root, "Temp", "collection_bootstrap_v1.json");
        if (File.Exists(artifact))
        {
            File.Delete(artifact);
        }

        var service = new CollectionBootstrapHostedService(
            new Mock<ILogger<CollectionBootstrapHostedService>>().Object,
            new GatherTradingDataParser());

        await service.StartAsync(CancellationToken.None);

        Assert.True(File.Exists(artifact));
        var text = await File.ReadAllTextAsync(artifact);
        Assert.Contains("\"gate\": \"PASS\"", text);
        Assert.Contains("\"bootstrap\": \"collection-scheduling-ready\"", text);
    }

    private static string FindRepoRoot()
    {
        var current = new DirectoryInfo(AppContext.BaseDirectory);
        while (current != null)
        {
            if (Directory.Exists(Path.Combine(current.FullName, ".git")))
            {
                return current.FullName;
            }
            current = current.Parent;
        }

        throw new InvalidOperationException("Repository root not found.");
    }
}
