using Hushian.Application.Models;
using Hushian.Application.Services;
using Hushian.WebApi;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.Reflection;
using System.Text;

namespace Hushian.Application
{
    public static class ApplicationServicesRegistration
    {
        public static void ConfigureApplicationServices(this IServiceCollection services,
            IConfiguration configuration)
        {
            services.AddAutoMapper(Assembly.GetExecutingAssembly());
            services.AddSignalR()
                .AddHubOptions<ChatNotificationHub>(options =>
                {
                    options.ClientTimeoutInterval = TimeSpan.FromMinutes(5);
                });
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero,
                    ValidIssuer = configuration["JwtSettings:Issuer"],
                    ValidAudience = configuration["JwtSettings:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:Key"]))
                };

                // ✅ لازم برای SignalR (WebSocket + توکن از query string یا header)
                o.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // فقط برای مسیرهای SignalR
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) &&
                            path.StartsWithSegments("/chatNotificationHub"))
                        {
                            context.Token = accessToken;
                        }

                        return Task.CompletedTask;
                    }
                };
            });
            services.AddScoped(typeof(AuthService));
            services.AddScoped(typeof(CompanyService));
            services.AddScoped(typeof(ConversationService));
            services.AddScoped(typeof(ChatService));
            services.AddScoped(typeof(ExperService));
            services.AddScoped(typeof(GroupService));
            services.AddScoped(typeof(PromptService));
            services.AddScoped(typeof(UserService));
            services.AddScoped(typeof(VerificationService));
            services.AddScoped(typeof(AIService));
            services.Configure<JwtSettings>(configuration.GetSection("JwtSettings"));
        }
    }
}
