using System;
using System.IO;
using Fast.Shared;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using TUnit.Core.Logging;
using TUnit.Engine.Logging;

namespace Test;

public static class GlobalSetup
{
    public static IConfiguration? Configuration { get; private set; }
    public static MockHostingEnvironment Env { get; } = new MockHostingEnvironment();
    public static string AssetsPath => Path.Combine(Env.ContentRootPath, "Assets");
    private static TUnitFrameworkLogger Logger { get; set; } = null!;

    [Before(Assembly)]
    public static void AssemblyInit(AssemblyHookContext _)
    {
        ProgramShared.IsDevEnv = true;

        var ctx = GlobalContext.Current;
        var loggerProp = ctx.GetType().GetProperty("GlobalLogger", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        Logger = (TUnitFrameworkLogger)loggerProp!.GetValue(ctx)!;

        Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
        Env.ContentRootPath = new DirectoryInfo(Directory.GetCurrentDirectory())?.FullName ?? "";
        ProgramShared.SetupDatabaseConnection();

        var db = ProgramShared.CreateContext(); // pre-load a context since it is slow on first run and skews test timing
        db.Database.GetDbConnection();
        LogInfo($"Database connection completed");
    }

    public static void LogInfo(string message)
    {
        Logger.LogInformation(message);
    }
}

public class MockHostingEnvironment : IHostEnvironment, IWebHostEnvironment
{
    public string EnvironmentName { get; set; } = Environments.Production;

    public string ApplicationName { get; set; } = "";

    public string WebRootPath { get; set; } = "";

    public string ContentRootPath { get; set; } = "";

    public IFileProvider ContentRootFileProvider { get; set; } = new PhysicalFileProvider("/");
    public IFileProvider WebRootFileProvider { get; set; } = new PhysicalFileProvider("/");

    IFileProvider IHostEnvironment.ContentRootFileProvider { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
}

