using Insight.Domain.Constants;
using Insight.Updater.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Insight.Updater.Windows
{
    internal class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = Host.CreateDefaultBuilder(args);
            builder.UseWindowsService();
            builder.UseSystemd();

            builder.ConfigureAppConfiguration(options =>
            {
                options.Sources.Clear();
                options.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                options.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true);
            });

            builder.ConfigureLogging(options =>
            {
                options.ClearProviders();
                options.SetMinimumLevel(LogLevel.Trace);

                options.AddSimpleConsole(options =>
                {
                    options.IncludeScopes = true;
                    options.SingleLine = true;
                    options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff ";
                });

                options.AddFile($"{Configuration.AppDirectory?.FullName}/" + "logs/updater_{Date}.log", LogLevel.Trace, fileSizeLimitBytes: 104857600, retainedFileCountLimit: 10, outputTemplate: "{Timestamp:o} [{Level:u3}] {Message} {NewLine}{Exception}");
            });

            builder.ConfigureServices((host, services) =>
            {
                // SERVICES
                services.AddHostedService<UpdateService>();

                // GLOBALS
                services.AddTransient(provider => new HttpClient(new HttpClientHandler
                {
                    ClientCertificateOptions = ClientCertificateOption.Manual,
                    ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => true
                }));
            });

            var host = builder.Build();
            await host.RunAsync().ConfigureAwait(false);
        }
    }
}