using CartWise.Application.Interfaces;
using CartWise.Infrastructure.Data;
using CartWise.Infrastructure.Identity;
using CartWise.Infrastructure.Integrations.OpenFoodFacts;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace CartWise.Infrastructure;

public static class InfrastructureServiceCollectionExtensions
{
    public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
    {
        var connectionString = configuration.GetConnectionString("DefaultConnection")
            ?? throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured.");

        services.AddDbContext<CartWiseDbContext>(options => options.UseSqlite(connectionString));
        services.AddScoped<IApplicationDbContext>(sp => sp.GetRequiredService<CartWiseDbContext>());

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.SignIn.RequireConfirmedAccount = false;
            })
            .AddEntityFrameworkStores<CartWiseDbContext>()
            .AddDefaultTokenProviders();

        var openFoodFactsBaseUrl = configuration["OpenFoodFacts:BaseUrl"] ?? "https://world.openfoodfacts.org/";
        services.AddHttpClient<IProductDataProvider, OpenFoodFactsProductDataProvider>(client =>
        {
            client.BaseAddress = new Uri(openFoodFactsBaseUrl);
            client.Timeout = TimeSpan.FromSeconds(10);
        });

        return services;
    }
}
