using System.IO;
using Xunit;
using ytLive.Helpers;
using ytLive.Models;

namespace ytLive.Tests;

public class TokenStoreTests
{
    private static string TempPath() =>
        Path.Combine(Path.GetTempPath(), "ytLive_tests", $"{Guid.NewGuid():N}.auth");

    [Fact]
    public void Save_Load_RoundtripsChannelAndTokens()
    {
        var path = TempPath();
        var channel = new YouTubeChannel
        {
            ChannelId = "UC123",
            DisplayName = "Test Channel",
            ProfileImageUrl = "http://example/thumb.jpg",
            AccessToken = "acc-token",
            RefreshToken = "refresh-token",
            TokenExpiry = DateTime.UtcNow.AddHours(1),
        };

        TokenStore.Save(channel, path);

        var loaded = TokenStore.Load(path);
        Assert.NotNull(loaded);
        Assert.Equal("UC123", loaded!.ChannelId);
        Assert.Equal("Test Channel", loaded.DisplayName);
        Assert.Equal("http://example/thumb.jpg", loaded.ProfileImageUrl);
        Assert.Equal("acc-token", loaded.AccessToken);
        Assert.Equal("refresh-token", loaded.RefreshToken);
        Assert.Equal(channel.TokenExpiry, loaded.TokenExpiry);
    }

    [Fact]
    public void Load_MissingFile_ReturnsNull()
    {
        Assert.Null(TokenStore.Load(TempPath()));
    }

    [Fact]
    public void Load_CorruptFile_ReturnsNull()
    {
        var path = TempPath();
        Directory.CreateDirectory(Path.GetDirectoryName(path)!);
        File.WriteAllBytes(path, [1, 2, 3, 4, 5]);
        Assert.Null(TokenStore.Load(path));
    }

    [Fact]
    public void Clear_RemovesSavedToken()
    {
        var path = TempPath();
        TokenStore.Save(new YouTubeChannel { DisplayName = "X" }, path);
        TokenStore.Clear(path);
        Assert.Null(TokenStore.Load(path));
    }
}
