using Application.Abstractions.Data;
using Application.Abstractions.Identity;
using Application.Abstractions.Messaging.Email;
using Infrastructure.Messaging.Email;
using Infrastructure.Persistence;
using Infrastructure.Persistence.Identity;
using Infrastructure.Storage;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SharedKernel;
using SharedKernel.Storage;
using StackExchange.Redis;

namespace Infrastructure
{
    public static class DependencyInjection
    {
        public static IServiceCollection AddAdminInfrastructure(this IServiceCollection services, IConfiguration configuration)
        {
            return services.AddDatabase(configuration).AddRedis(configuration).AddServices().AddHealthChecks(configuration);
        }

        // SQL 연결
        private static IServiceCollection AddDatabase(this IServiceCollection services, IConfiguration configuration)
        {
            var dbConn = configuration.GetConnectionString("DefaultConnection");
            if (string.IsNullOrWhiteSpace(dbConn))
            {
                throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured.");
            }

            services.AddDbContext<AppDbContext>(options => options.UseSqlServer(dbConn));
            services.AddDbContext<IdentityDbContext>(options => options.UseSqlServer(dbConn));

            services.AddScoped<IAppDbContext>(sp => sp.GetRequiredService<AppDbContext>());

            return services;
        }

        // Redis 연결
        public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
        {
            var settings = configuration.Get<AppSettings>()!;
            var redis = ConnectionMultiplexer.Connect(settings.Redis.DefaultConnection);

            services.AddSingleton<IConnectionMultiplexer>(redis);
            services.AddDataProtection().SetApplicationName(settings.App.Name).PersistKeysToStackExchangeRedis(redis, settings.Redis.DataProtectionKey).SetDefaultKeyLifetime(settings.Redis.DefaultKeyLifetime); // 기본 90일 회전

            // Distributed Cache 설정
            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = settings.Redis.DefaultConnection;
                options.InstanceName = settings.Redis.CachePrefix;
            });

            return services;
        }

        private static IServiceCollection AddServices(this IServiceCollection services)
        {

            services.AddTransient<IMailService, MailService>();
            services.AddTransient<IEmailSender, IdentityEmailSender>();
            services.AddScoped<IFileStorage, LocalFileStorage>();
            services.AddScoped<IEditorImageService, EditorImageService>();
            services.AddScoped<IIdentityUserReader, IdentityUserReader>();
            services.AddScoped<IIdentityUserWriter, IdentityUserWriter>();
            services.AddScoped<IIdentityRoleReader, IdentityRoleReader>();
            services.AddScoped<IIdentityRoleWriter, IdentityRoleWriter>();

            return services;
        }

        private static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration)
        {
            var settings = configuration.Get<AppSettings>()!;

            services.AddHealthChecks().AddSqlServer(settings.ConnectionStrings.DefaultConnection).AddRedis(settings.Redis.DefaultConnection);

            return services;
        }
    }
}