using System.Text.Json;
using FluentAssertions;
using NexusReader.Application.Common;
using NexusReader.Application.DTOs.Media;
using Xunit;

namespace NexusReader.Application.Tests.Services;

public class AutosaveEngineTests
{
    [Fact]
    public void SerializeAndDeserialize_LocalBackupEnvelope_Succeeds()
    {
        // Arrange
        var envelope = new LocalBackupEnvelope
        {
            ChapterId = Guid.NewGuid(),
            Timestamp = DateTime.UtcNow.AddMinutes(-10),
            MarkdownContent = "# Hello Autosave"
        };

        // Act
        var json = JsonSerializer.Serialize(envelope, AppJsonContext.Default.LocalBackupEnvelope);
        var deserialized = JsonSerializer.Deserialize(json, AppJsonContext.Default.LocalBackupEnvelope);

        // Assert
        deserialized.Should().NotBeNull();
        deserialized!.ChapterId.Should().Be(envelope.ChapterId);
        deserialized.MarkdownContent.Should().Be(envelope.MarkdownContent);
        // Truncate milliseconds to avoid precision discrepancies in text representation
        deserialized.Timestamp.ToUniversalTime().Date.Should().Be(envelope.Timestamp.ToUniversalTime().Date);
    }

    [Fact]
    public void SerializeAndDeserialize_AutosaveChapterRequest_Succeeds()
    {
        // Arrange
        var request = new AutosaveChapterRequest("# Content to Autosave");

        // Act
        var json = JsonSerializer.Serialize(request, AppJsonContext.Default.AutosaveChapterRequest);
        var deserialized = JsonSerializer.Deserialize(json, AppJsonContext.Default.AutosaveChapterRequest);

        // Assert
        deserialized.Should().NotBeNull();
        deserialized!.MarkdownContent.Should().Be(request.MarkdownContent);
    }

    [Fact]
    public void BackupEviction_CheckAgeLogic_EvictsCorrectly()
    {
        // Arrange
        var now = DateTime.UtcNow;
        var freshTimestamp = now.AddDays(-6);
        var expiredTimestamp = now.AddDays(-8);

        // Act & Assert
        (now - freshTimestamp).TotalDays.Should().BeLessThanOrEqualTo(7.0);
        (now - expiredTimestamp).TotalDays.Should().BeGreaterThan(7.0);
    }
}
