using System;
using System.Collections.Generic;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using StellaOps.Feedser.Source.Vndr.Apple.Internal;
using StellaOps.Feedser.Source.Vndr.Apple.Tests.Apple;
using Xunit;

namespace StellaOps.Feedser.Source.Vndr.Apple.Tests;

public sealed class AppleLiveRegressionTests
{
    private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web)
    {
        WriteIndented = false,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
    };

    public static IEnumerable<object[]> FixtureCases
    {
        get
        {
            foreach (var definition in AppleFixtureManager.Fixtures)
            {
                yield return new object[] { definition.ArticleId };
            }
        }
    }

    [Theory]
    [MemberData(nameof(FixtureCases))]
    public async Task Parser_SanitizedFixture_MatchesExpectedDto(string articleId)
    {
        var updateFlag = Environment.GetEnvironmentVariable("UPDATE_APPLE_FIXTURES");
        if (!string.IsNullOrEmpty(updateFlag))
        {
            Console.WriteLine($"[AppleFixtures] UPDATE_APPLE_FIXTURES={updateFlag}");
        }
        await AppleFixtureManager.EnsureUpdatedAsync();
        var expected = AppleFixtureManager.ReadExpectedDto(articleId);
        var html = AppleFixtureManager.ReadFixture($"{articleId}.html");

        var entry = new AppleIndexEntry(
            UpdateId: articleId,
            ArticleId: articleId,
            Title: expected.Title,
            PostingDate: expected.Published,
            DetailUri: new Uri($"https://support.apple.com/en-us/{articleId}"),
            Products: Array.Empty<AppleIndexProduct>(),
            IsRapidSecurityResponse: expected.RapidSecurityResponse);

        var dto = AppleDetailParser.Parse(html, entry);
        var actualJson = JsonSerializer.Serialize(dto, SerializerOptions);
        var expectedJson = JsonSerializer.Serialize(expected, SerializerOptions);
        Assert.Equal(expectedJson, actualJson);
    }
}
