using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Configuration;
using Serilog.Sinks.MSSqlServer;
using System;

namespace NetworkResurrector.Api.Extensions
{
    internal static class LoggingExtensions
    {
        internal static LoggerSinkConfiguration ConfiguredDestinations(this LoggerSinkConfiguration writeTo, IConfiguration configuration)
        {
            var sqlServerEnabled = configuration.GetValue<bool>("Logs:SqlServer:Enabled");
            var sqlServerConnection = configuration.GetValue<string>("Logs:SqlServer:Connection");
            var seqEnabled = configuration.GetValue<bool>("Logs:Seq:Enabled");
            var seqUrl = configuration.GetValue<string>("Logs:Seq:Url");
            var seqApiKey = configuration.GetValue<string>("Logs:Seq:ApiKey");

            if (sqlServerEnabled && string.IsNullOrWhiteSpace(sqlServerConnection))
                throw new Exception("If SqlServer logging is enabled, the SqlServer connection must be configured.");
            if (seqEnabled && string.IsNullOrWhiteSpace(seqUrl))
                throw new Exception("If Seq logging is enabled, the Seq URL must be configured.");

            if (sqlServerEnabled)
            {
                var columnOptions = new ColumnOptions();
                columnOptions.Store.Remove(StandardColumn.Properties);
                columnOptions.Store.Remove(StandardColumn.MessageTemplate);
                columnOptions.Store.Add(StandardColumn.LogEvent);
                var mssqlSinkOptions = new MSSqlServerSinkOptions() { AutoCreateSqlTable = true, TableName = "__Logs" };

                writeTo.MSSqlServer(sqlServerConnection, mssqlSinkOptions, columnOptions: columnOptions);
            }

            if (seqEnabled)
                writeTo.Seq(seqUrl, apiKey: seqApiKey.Nullify());

            return writeTo;
        }
    }
}
