using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;

namespace Kit.Helpers.Config;

public class StaticFileConfigBuilder<TIApplicationBuilder>
        where TIApplicationBuilder : IApplicationBuilder
{
    private readonly List<string> _contentModules;

    private Action<StaticFileResponseContext> _onPrepareResponse;

    internal StaticFileConfigBuilder()
    {
        _contentModules = new List<string>();
        _onPrepareResponse = ctx =>
        {
            ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=3600");
        };
    }

    public StaticFileConfigBuilder<TIApplicationBuilder> WithContentModule(string moduleName)
    {
        _contentModules.Add(moduleName);
        return this;
    }

    public StaticFileConfigBuilder<TIApplicationBuilder> WithOnPrepareResponse(Action<StaticFileResponseContext> ctx)
    {
        _onPrepareResponse = ctx;
        return this;
    }

    internal TIApplicationBuilder Apply(TIApplicationBuilder app)
    {
        IWebHostEnvironment env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
        // основной wwwroot
        List<IFileProvider> fileProviderItems = new List<IFileProvider> { env.WebRootFileProvider };

        if (_contentModules.Count > 0)
        {
#if DEBUG
            fileProviderItems.Add(new PhysicalFileProvider(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot")));
#else
            fileProviders.AddRange(_contentModules.Select(moduleName => new PhysicalFileProvider(Path.Combine(_env.ContentRootPath, "wwwroot", "_content", moduleName))));
#endif
        }

        var fileProvider = new CompositeFileProvider(fileProviderItems);
        env.WebRootFileProvider = fileProvider;
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = fileProvider,
            RequestPath = "",
            OnPrepareResponse = _onPrepareResponse
        });

        return app;
    }
}

public static class StaticFileConfigBuilderExt
{

    public static TIApplicationBuilder UseCustomStaticFiles<TIApplicationBuilder>(this TIApplicationBuilder app, Action<StaticFileConfigBuilder<TIApplicationBuilder>> options)
        where TIApplicationBuilder : IApplicationBuilder
    {
        var config = new StaticFileConfigBuilder<TIApplicationBuilder>();

        if (options != null)
            options(config);

        config.Apply(app);

        return app;
    }
}