namespace Hims.Api.Extensions
{
    using System.Text.Json;
    using System.Text.Json.Serialization;
    using AutoMapper;
    using Filters;
    using Infrastructure.Helpers.Middleware;
    using Infrastructure.Repositories.Middleware;
    using Infrastructure.Services.Middleware;
    using Microsoft.AspNetCore.Http.Features;
    using Microsoft.Extensions.DependencyInjection;
    using Profiles;
    using Senders;

    /// <summary>
    /// The service collection extensions.
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// The register services.
        /// </summary>
        /// <param name="services">
        /// The services.
        /// </param>
        /// <returns>
        /// The <see cref="IServiceCollection"/>.
        /// </returns>
        public static IServiceCollection RegisterServices(this IServiceCollection services)
        {

            services.AddCors(options =>
                {
                    options.AddPolicy(
                        "CorsPolicy",
                        builder => builder.AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials().SetIsOriginAllowed(origin => true));
                });
            services.AddOptions();
            services.RegisterHelpers();
            services.RegisterRepositories();
            services.RegisterBusinessServices();
            services.AddTransient<ISMSSender, SMSSender>();
            services.AddTransient<IEmailSender, EmailSender>();
            services.AddTransient<IWhatsAppSMSSender, WhatsAppSMSSender>();

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            var mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);

            services.AddControllersWithViews(config =>
            {
                config.Filters.Add(typeof(ExceptionFilter));
                config.RespectBrowserAcceptHeader = false;
                config.ReturnHttpNotAcceptable = true;
            })
            .AddJsonOptions(a =>
            {
                a.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                a.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            });

            services.Configure<FormOptions>(
            x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;
            });

            services.AddAntiforgery(options => options.SuppressXFrameOptionsHeader = true);
            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");



            services.AddSignalR();

            return services;
        }
    }
}