using System.Text.Json;
using Backend.Services;
using Microsoft.EntityFrameworkCore;

namespace Backend.Data;

public static partial class SeedDataBootstrapper
{
    private static async Task EnsureSiteSettingsAsync(AwardsDbContext db)
    {
        var settings = await db.SiteSettings.FirstOrDefaultAsync(item => item.Id == 1);
        if (settings is null)
        {
            return;
        }

        if (!HasValidSiteArray(settings.FaqJson, "question", "answer"))
        {
            settings.FaqJson = JsonSerializer.Serialize(SeedCatalog.SiteFaqSeeds.Select(item => new
            {
                question = item.Question,
                answer = item.Answer,
            }));
        }

        if (!HasValidSiteArray(settings.SocialLinksJson, "label", "platform", "url"))
        {
            settings.SocialLinksJson = JsonSerializer.Serialize(SeedCatalog.SiteSocialSeeds.Select(item => new
            {
                label = item.Label,
                platform = item.Platform,
                url = item.Url,
                icon = item.Icon,
                showOnHost = true,
                showOnCommunity = true,
            }));
        }

        if (!HasValidRiskRules(settings.RiskRulesJson))
        {
            settings.RiskRulesJson = RiskRuleSettings.Serialize(RiskRuleSettings.Defaults);
        }

        if (string.IsNullOrWhiteSpace(settings.ImprintContent))
        {
            settings.ImprintContent = SeedCatalog.DefaultImprintContent;
        }

        if (string.IsNullOrWhiteSpace(settings.ContactContent))
        {
            settings.ContactContent = SeedCatalog.DefaultContactContent;
        }

        if (string.IsNullOrWhiteSpace(settings.SponsorsContent))
        {
            settings.SponsorsContent = SeedCatalog.DefaultSponsorsContent;
        }
    }

    private static bool HasValidSiteArray(string? json, params string[] requiredKeys)
    {
        if (string.IsNullOrWhiteSpace(json))
        {
            return false;
        }

        try
        {
            using var document = JsonDocument.Parse(json);
            if (document.RootElement.ValueKind != JsonValueKind.Array)
            {
                return false;
            }

            return document.RootElement.EnumerateArray().Any(item =>
                item.ValueKind == JsonValueKind.Object
                && requiredKeys.All(key =>
                    item.TryGetProperty(key, out var value)
                    && value.ValueKind == JsonValueKind.String
                    && !string.IsNullOrWhiteSpace(value.GetString())));
        }
        catch (JsonException)
        {
            return false;
        }
    }

    private static bool HasValidRiskRules(string? json) =>
        RiskRuleSettings.Read(new Backend.Domain.SiteSettings { RiskRulesJson = json ?? string.Empty }).Length == RiskRuleSettings.Defaults.Length;
}
