using Backend.Data;
using Microsoft.EntityFrameworkCore;

namespace Backend.Endpoints;

public static partial class PublicEndpoints
{
    private static async Task<IResult> GetHostImage(AwardsDbContext db)
    {
        var settings = await db.SiteSettings
            .AsNoTracking()
            .Where(item => item.Id == 1)
            .Select(item => new
            {
                item.HostImageData,
                item.HostImageContentType,
                item.HostImageUpdatedAt,
            })
            .FirstOrDefaultAsync();

        if (settings?.HostImageData is not { Length: > 0 } imageData
            || string.IsNullOrWhiteSpace(settings.HostImageContentType))
        {
            return Results.NotFound();
        }

        var entityTag = settings.HostImageUpdatedAt?.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture)
            ?? imageData.Length.ToString(System.Globalization.CultureInfo.InvariantCulture);
        return Results.File(
            imageData,
            settings.HostImageContentType,
            entityTag: new Microsoft.Net.Http.Headers.EntityTagHeaderValue($"\"host-{entityTag}\""),
            lastModified: settings.HostImageUpdatedAt);
    }
}
