using Ikar.Server.Data.Entities;
using Ikar.Server.Infrastructure.Auth;
using Ikar.Shared;
using Microsoft.AspNetCore.Http;

namespace Ikar.Server.Tests;

public sealed class ClientVersionRequestReaderTests
{
    [Fact]
    public void Read_UsesClientVersionHeaders()
    {
        var context = new DefaultHttpContext();
        context.Request.Headers[ClientVersionMetadata.PlatformHeaderName] = " android ";
        context.Request.Headers[ClientVersionMetadata.VersionCodeHeaderName] = "168";
        context.Request.Headers[ClientVersionMetadata.VersionNameHeaderName] = "3.55";

        var snapshot = ClientVersionRequestReader.Read(context.Request);

        Assert.Equal("android", snapshot.ClientPlatform);
        Assert.Equal(168, snapshot.ClientVersionCode);
        Assert.Equal("3.55", snapshot.ClientVersionName);
    }

    [Fact]
    public void Apply_DoesNotClearExistingClientVersionWhenSnapshotIsEmpty()
    {
        var session = new UserSession
        {
            ClientPlatform = "android",
            ClientVersionCode = 168,
            ClientVersionName = "3.55"
        };

        var changed = ClientVersionRequestReader.Apply(session, new(null, null, null));

        Assert.False(changed);
        Assert.Equal("android", session.ClientPlatform);
        Assert.Equal(168, session.ClientVersionCode);
        Assert.Equal("3.55", session.ClientVersionName);
    }

    [Fact]
    public void Apply_StoresClientVersionOnPushDevice()
    {
        var device = new PushDevice();

        var changed = ClientVersionRequestReader.Apply(device, new("android", 168, "3.55"));

        Assert.True(changed);
        Assert.Equal("android", device.ClientPlatform);
        Assert.Equal(168, device.ClientVersionCode);
        Assert.Equal("3.55", device.ClientVersionName);
    }
}
