using Backend.Contracts;
using Backend.Data;
using Microsoft.EntityFrameworkCore;

namespace Backend.Endpoints;

public static partial class PublicEndpoints
{
    private static async Task<IResult> GetSiteStatus(AwardsDbContext db, IConfiguration configuration)
    {
        var settings = await db.SiteSettings.AsNoTracking().FirstOrDefaultAsync(item => item.Id == 1);
        if (settings is null)
        {
            return Results.Ok(new PublicSiteStatusResponse(
                IsDemoLoginEnabled(configuration),
                false,
                "Sternenpause",
                "Die Award-Galaxie wird gerade liebevoll poliert. Schau gleich wieder vorbei."));
        }

        return Results.Ok(new PublicSiteStatusResponse(
            ResolveDemoLoginEnabled(settings, configuration),
            settings.MaintenanceModeEnabled,
            string.IsNullOrWhiteSpace(settings.MaintenanceTitle) ? "Sternenpause" : settings.MaintenanceTitle,
            string.IsNullOrWhiteSpace(settings.MaintenanceMessage)
                ? "Die Award-Galaxie wird gerade liebevoll poliert. Schau gleich wieder vorbei."
                : settings.MaintenanceMessage));
    }

    private static bool ResolveDemoLoginEnabled(Backend.Domain.SiteSettings settings, IConfiguration configuration)
    {
        var usesDatabaseDemo = settings.DemoLoginManagedByDatabase;
        if (!usesDatabaseDemo)
        {
            return IsDemoLoginEnabled(configuration);
        }

        return settings.DemoLoginEnabled && HasDatabaseDemoCredentials(settings);
    }

    private static bool IsDemoLoginEnabled(IConfiguration configuration)
    {
        var rawValue = configuration["VTSA_DEMO_LOGIN_ENABLED"]
            ?? configuration["DemoAdmin:Enabled"];

        return bool.TryParse(rawValue, out var enabled) && enabled;
    }

    private static bool HasDatabaseDemoCredentials(Backend.Domain.SiteSettings settings) =>
        !string.IsNullOrWhiteSpace(settings.DemoLoginEmail)
        && !string.IsNullOrWhiteSpace(settings.DemoLoginPasswordHash)
        && !string.IsNullOrWhiteSpace(settings.DemoLoginPasswordSalt);
}
