using Microsoft.AspNetCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PhotoHost.Endpoints; // Import ImgEndpoint.cs

namespace PhotoHost
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add Kestrel configuration to read from appsettings.json
            builder.WebHost.UseKestrel((context, options) =>
            {
                options.Configure(context.Configuration.GetSection("Kestrel"));
            });

            // Add ImageService to DI container
            builder.Services.AddSingleton<ImageService>();
            builder.Services.AddAuthorization();

            var app = builder.Build();

            var logger = app.Services.GetRequiredService<ILogger<Program>>();
            var photoFolder = app.Configuration["PhotoFolder"];

            // Log the photo folder path from configuration
            if (!string.IsNullOrEmpty(photoFolder))
            {
                logger.LogInformation("PhotoFolder path: {PhotoFolder}", photoFolder);
            }
            else
            {
                logger.LogWarning("PhotoFolder path is not set in configuration.");
            }

            // Global exception handling middleware
            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
                    var exception = exceptionHandlerPathFeature?.Error;

                    // Log the unhandled exception
                    logger.LogError(exception, "An unhandled exception occurred");

                    context.Response.StatusCode = 500;
                    context.Response.ContentType = "application/json";

                    // Return a simple error message
                    await context.Response.WriteAsync(new
                    {
                        error = "Internal server error. Please try again later."
                    }.ToString() ?? "Internal server error.");
                });
            });

            app.UseAuthorization();

            // Map the img endpoint from a separate file
            app.MapImgEndpoint();

            app.Run();
        }
    }
}
