﻿using DailyWork;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace IntegrationTests.Helpers;

public class TestWebApplicationFactory<TProgram>
    : WebApplicationFactory<TProgram> where TProgram : class
{
    protected override IHost CreateHost(IHostBuilder builder)
    {
        /*builder.ConfigureHostConfiguration(config =>
        {
            config.AddInMemoryCollection(new Dictionary<string, string?> { { "EmailAddress", "test1@Contoso.com" } });
        });*/

        builder.ConfigureServices(services =>
        {
            // Remove any existing WorkDb registrations (options, context, implementation)
            var descriptorsToRemove = services.Where(d => d.ServiceType == typeof(DbContextOptions<WorkDb>)
                                                         || d.ServiceType == typeof(WorkDb)
                                                         || d.ImplementationType == typeof(WorkDb))
                                             .ToList();

            foreach (var d in descriptorsToRemove)
            {
                services.Remove(d);
            }

            // Register WorkDb for tests using Sqlite. Do not call UseInternalServiceProvider; let EF manage its service provider.
            services.AddDbContext<WorkDb>((serviceProvider, options) =>
            {
                var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                options.UseSqlite($"Data Source={Path.Join(path, "Integration_tests.db")}");
            });
        });

        return base.CreateHost(builder);
    }
}
