using System;
using System.Globalization;
using Microsoft.Extensions.Options;
using QRRapidoApp.Models.Ads;

namespace QRRapidoApp.Services.Ads
{
    public class ConfigurationAdSlotProvider : IAdSlotConfigurationProvider
    {
        private readonly IOptionsSnapshot<AdsConfigurationOptions> _options;

        public ConfigurationAdSlotProvider(IOptionsSnapshot<AdsConfigurationOptions> options)
        {
            _options = options;
        }

        public AdSlotConfiguration GetSlot(string slotKey, string? cultureName = null)
        {
            var resolvedCulture = cultureName;
            if (string.IsNullOrWhiteSpace(resolvedCulture))
            {
                resolvedCulture = CultureInfo.CurrentUICulture?.Name;
            }

            var slot = _options.Value.GetSlot(slotKey, resolvedCulture);

            if (string.Equals(slot.Provider, "Affiliate", StringComparison.OrdinalIgnoreCase))
            {
                if (slot.Affiliate == null || slot.Affiliate.IsEmpty())
                {
                    // Fallback gracefully to AdSense if affiliate content is not properly configured.
                    return new AdSlotConfiguration
                    {
                        Provider = "AdSense",
                        AdSenseSlotId = slot.AdSenseSlotId
                    };
                }

                slot.Provider = "Affiliate"; // normalize casing
            }
            else
            {
                slot.Provider = "AdSense";
            }

            return slot;
        }
    }
}
