using System;
using System.IO;
using System.Linq;
using System.Threading;
using FluentAssertions;
using MarcusLaw.OutlookAddin.Core.Logging;
using Xunit;

namespace MarcusLaw.OutlookAddin.Tests.Logging
{
    public class LoggerFactoryTests : IDisposable
    {
        private readonly string _tempDir;

        public LoggerFactoryTests()
        {
            _tempDir = Path.Combine(Path.GetTempPath(), "OutlookAddinLogTests-" + Guid.NewGuid().ToString("N"));
        }

        public void Dispose()
        {
            try { Directory.Delete(_tempDir, recursive: true); } catch { }
        }

        [Fact]
        public void Init_CreatesLogDirectoryAndWritesFile()
        {
            var logger = LoggerFactory.Init(_tempDir);
            try
            {
                logger.Information("hello {Name}", "world");
            }
            finally
            {
                Serilog.Log.CloseAndFlush();
                (logger as IDisposable)?.Dispose();
            }

            Directory.Exists(_tempDir).Should().BeTrue();
            var files = Directory.GetFiles(_tempDir, "addin-*.log");
            files.Should().NotBeEmpty();

            using var fs = new FileStream(files[0], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using var sr = new StreamReader(fs);
            var contents = sr.ReadToEnd();
            contents.Should().Contain("hello world");
        }
    }
}
