using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog.Events;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Serilog.Extensions.Hosting;
using Microsoft.AspNetCore.Builder;

namespace SumaTube.Crosscutting.Logging.Configuration
{
    public static class SerilogConfiguration
    {
        public static LoggerConfiguration SetLoggerConfiguration(this WebApplicationBuilder builder, LoggerConfiguration config, IServiceProvider services, IConfiguration configuration)
        {
            var workspace = configuration["Serilog:Properties:Workspace"];
            var seqServer = configuration.GetValue<string>("Serilog:WriteTo:2:Args:serverUrl"); ;

            config
                .ReadFrom.Configuration(configuration)
                .ReadFrom.Services(services)
                .Enrich.FromLogContext()
                .Enrich.WithEnvironmentName()
                .Enrich.WithMachineName()
                .Enrich.WithProperty("Application", "SumaTube")
                .Enrich.WithProperty("Workspace", workspace)
                .WriteTo.Seq(seqServer)
                ;

            return config;
        }


        public static IServiceCollection AddSerilogServices(this IServiceCollection services, IConfiguration configuration, IHostEnvironment environment)
        {
            // Obtenha o workspace do Seq baseado no ambiente
            //var workspace = environment.IsDevelopment() ? "Dev" : "Prod";

            services.AddSingleton<DiagnosticContext>();

            var workspace = configuration["Serilog:Properties:Workspace"];

            // Crie o logger usando a configuração
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .Enrich.FromLogContext()
                .Enrich.WithMachineName()
                .Enrich.WithEnvironmentName()
                //.Enrich.WithProperty("Workspace", workspace) // Adiciona explicitamente o workspace
                .CreateLogger();

            // Registra o logger no container de DI
            services.AddSingleton(Log.Logger);

            return services;
        }

        // Método opcional para configuração direta sem usar appsettings.json
        public static IServiceCollection AddSerilogServicesWithCode(
            this IServiceCollection services,
            IHostEnvironment environment)
        {
            services.AddSingleton<DiagnosticContext>();

            // Defina as configurações do Seq baseado no ambiente
            var (workspace, apiKey) = environment.IsDevelopment()
                ? ("Dev", "sua-api-key-dev")
                : ("Prod", "sua-api-key-prod");

            // Configuração básica para ambos ambientes
            var loggerConfig = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.FromLogContext()
                .Enrich.WithMachineName()
                .Enrich.WithEnvironmentUserName()
                .Enrich.WithThreadId()
                .Enrich.WithProperty("Application", "SumaTube")
                .Enrich.WithProperty("Environment", environment.EnvironmentName)
                .Enrich.WithProperty("Workspace", workspace);

            // Adicione destinos específicos por ambiente
            if (environment.IsDevelopment())
            {
                loggerConfig
                    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                    .WriteTo.Console()
                    .WriteTo.File("logs/dev-app-.log", rollingInterval: RollingInterval.Day);
            }
            else // Produção ou outros ambientes
            {
                loggerConfig
                    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                    .MinimumLevel.Override("System", LogEventLevel.Error)
                    .WriteTo.File("logs/prod-app-.log", rollingInterval: RollingInterval.Day);
            }

            // Adicione o Seq para ambos ambientes, mas com configurações diferentes
            //loggerConfig.WriteTo.Seq(
            //    "http://logs-ingest.carneiro.ddnsfree.com",
            //    apiKey: apiKey);
            loggerConfig.WriteTo.Seq(
                "http://logs.carneiro.ddnsfree.com:5341");

            Log.Logger = loggerConfig.CreateLogger();

            // Registra o logger no container de DI
            services.AddSingleton(Log.Logger);

            return services;
        }
    }
}
