using System.Reflection;
using JobTrackerApi.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;

namespace JobTrackerApi.Tests;

public sealed class CvExportRetentionTests
{
    [Fact]
    public void Export_pruning_removes_only_expired_date_directories()
    {
        var root = Path.Combine(Path.GetTempPath(), $"jobtracker-export-retention-{Guid.NewGuid():N}");
        var exportsRoot = Path.Combine(root, "CvExports");
        var owner = AppPaths.GetOwnerStorageKey("user-1");
        var old = Path.Combine(exportsRoot, owner, "20260101");
        var keep = Path.Combine(exportsRoot, owner, "20260731");
        var legacyOld = Path.Combine(exportsRoot, "20260101");
        var unrelated = Path.Combine(exportsRoot, "manual");
        Directory.CreateDirectory(old);
        Directory.CreateDirectory(keep);
        Directory.CreateDirectory(legacyOld);
        Directory.CreateDirectory(unrelated);

        try
        {
            var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?> { ["Data:Root"] = root }).Build();
            var environment = new Mock<IHostEnvironment>();
            environment.SetupGet(x => x.ContentRootPath).Returns(root);
            var exporter = new PlaywrightCvPdfExporter(new AppPaths(config, environment.Object), NullLogger<PlaywrightCvPdfExporter>.Instance, config);
            var prune = typeof(PlaywrightCvPdfExporter).GetMethod("PruneExpiredExports", BindingFlags.Instance | BindingFlags.NonPublic)!;

            prune.Invoke(exporter, [new DateOnly(2026, 7, 1)]);

            Assert.False(Directory.Exists(old));
            Assert.True(Directory.Exists(keep));
            Assert.False(Directory.Exists(legacyOld));
            Assert.True(Directory.Exists(unrelated));
        }
        finally
        {
            if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
        }
    }
}
