using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using SocialService.Infrastructure;

namespace SocialService.FunctionalTests;

/// <summary>
/// EN: Custom WebApplicationFactory for functional tests.
/// VI: WebApplicationFactory tùy chỉnh cho functional tests.
/// </summary>
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseEnvironment("Testing");
        
        builder.ConfigureServices(services =>
        {
            // EN: Remove ALL database-related services
            // VI: Xóa TẤT CẢ các services liên quan đến database
            var descriptorsToRemove = services.Where(d =>
                d.ServiceType == typeof(DbContextOptions<SocialServiceContext>) ||
                d.ServiceType == typeof(DbContextOptions) ||
                d.ServiceType == typeof(SocialServiceContext) ||
                d.ServiceType.Name.Contains("DbContextOptions") ||
                d.ImplementationType?.FullName?.Contains("Npgsql") == true ||
                d.ImplementationType?.FullName?.Contains("PostgreSql") == true ||
                d.ServiceType.FullName?.Contains("Npgsql") == true ||
                d.ServiceType.FullName?.Contains("HealthCheck") == true
            ).ToList();

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

            // EN: Add in-memory database for testing
            // VI: Thêm in-memory database để test
            var dbName = $"TestDatabase_{Guid.NewGuid()}";
            services.AddDbContext<SocialServiceContext>(options =>
            {
                options.UseInMemoryDatabase(dbName);
            });

            // EN: Add basic health checks (without database dependency)
            // VI: Thêm basic health checks (không phụ thuộc database)
            services.AddHealthChecks();
        });
    }
}
