using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OI.Metrology.Shared.DataModels;
using OI.Metrology.Shared.Models.Stateless;

namespace OI.Metrology.Tests;

[TestClass]
public class UnitTestPinController
{

#pragma warning disable CS8618

    private static ILogger? _Logger;
    private static string _ControllerName;
    private static TestContext _TestContext;
    private static WebApplicationFactory<Server.Program>? _WebApplicationFactory;

#pragma warning restore

    [ClassInitialize]
    public static void ClassInitAsync(TestContext testContext)
    {
        _TestContext = testContext;
        _WebApplicationFactory = new WebApplicationFactory<Server.Program>();
        IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider;
        _Logger = serviceProvider.GetRequiredService<ILogger<Server.Program>>();
        _ControllerName = nameof(Server.ApiControllers.PinController)[..^10];
    }

    [TestMethod]
    public void TestControllerName()
    {
        _Logger?.LogInformation("Starting Web Application");
        Assert.AreEqual(IPinController<string>.GetRouteName(), _ControllerName);
        _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName);
    }

    [TestMethod]
    public void GetPinnedTable()
    {
        _Logger?.LogInformation("Starting Web Application");
        IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider;
        IMetrologyRepository? metrologyRepository = serviceProvider?.GetRequiredService<IMetrologyRepository>();
        IPinRepository? pinRepository = serviceProvider?.GetRequiredService<IPinRepository>();
        Assert.IsTrue(metrologyRepository is not null);
        Result<Pinned[]>? result = pinRepository?.GetPinnedTable(metrologyRepository, id: 1, cde_id: null, biorad_id: null, rds: null);
        Assert.IsNotNull(result?.Results);
        _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName);
    }

    [TestMethod]
    public async Task GetPinnedTableApi()
    {
        HttpClient? httpClient = _WebApplicationFactory?.CreateClient();
        _Logger?.LogInformation("Starting Web Application");
        Assert.IsTrue(httpClient is not null);
        string? json = await httpClient.GetStringAsync($"api/{_ControllerName}/-1/pinned");
        File.WriteAllText(Path.Combine(AppContext.BaseDirectory, $"{_ControllerName}-{nameof(GetPinnedTable)}.json"), json);
        Result<Pinned[]>? result = System.Text.Json.JsonSerializer.Deserialize<Result<Pinned[]>>(json);
        Assert.IsNotNull(result?.Results);
        _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName);
    }

}