using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace PhotoHost.Endpoints
{
    public static class ImgEndpoint
    {
        // Method to map the image endpoint (/img/{sku}) in the app
        public static void MapImgEndpoint(this IEndpointRouteBuilder endpoints)
        {
            endpoints.MapGet("/img/{sku}", async (string sku, HttpContext httpContext, ImageService imageService) =>
            {
                try
                {
                    var imageFile = imageService.GetImage(sku); // Get the image file by SKU
                    if (imageFile == null)
                    {
                        httpContext.Response.StatusCode = StatusCodes.Status404NotFound;
                        await httpContext.Response.WriteAsync("Image not found");
                        return;
                    }

                    // Determine the MIME type based on file extension
                    var mimeType = imageFile.Extension switch
                    {
                        ".jpg" or ".jpeg" => "image/jpeg",
                        ".png" => "image/png",
                        _ => "application/octet-stream"
                    };

                    // Set the response headers and write the image data to the response body
                    httpContext.Response.ContentType = mimeType;
                    httpContext.Response.Headers.ETag = imageFile.ETag;
                    await httpContext.Response.Body.WriteAsync(imageFile.Data.AsMemory(0, imageFile.Data.Length));
                }
                catch (Exception ex)
                {
                    // Handle any unexpected errors
                    httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                    await httpContext.Response.WriteAsync("Internal server error. Please try again later.");
                    Console.WriteLine($"Error processing file {sku}: {ex.Message}");
                }
            });
        }
    }
}
