using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using OF_DL.Models;
using OF_DL.Services;

namespace OF_DL.Tests.Services;

[Collection("NonParallel")]
public class AuthServiceTests
{
    [Fact]
    public async Task LoadFromFileAsync_ReturnsFalseWhenMissing()
    {
        using TempFolder temp = new();
        using CurrentDirectoryScope _ = new(temp.Path);
        AuthService service = CreateService();

        bool result = await service.LoadFromFileAsync();

        Assert.False(result);
        Assert.Null(service.CurrentAuth);
    }

    [Fact]
    public async Task SaveToFileAsync_WritesAuthFile()
    {
        using TempFolder temp = new();
        using CurrentDirectoryScope _ = new(temp.Path);
        AuthService service = CreateService();
        service.CurrentAuth = new Auth
        {
            UserId = "123",
            UserAgent = "agent",
            XBc = "xbc",
            Cookie = "auth_id=123; sess=abc;"
        };

        await service.SaveToFileAsync();

        Assert.True(File.Exists("auth.json"));
        string json = await File.ReadAllTextAsync("auth.json");
        Auth? saved = JsonConvert.DeserializeObject<Auth>(json);
        Assert.NotNull(saved);
        Assert.Equal("123", saved.UserId);
        Assert.Equal("agent", saved.UserAgent);
        Assert.Equal("xbc", saved.XBc);
        Assert.Equal("auth_id=123; sess=abc;", saved.Cookie);
    }

    [Fact]
    public void ValidateCookieString_NormalizesAndPersists()
    {
        using TempFolder temp = new();
        using CurrentDirectoryScope _ = new(temp.Path);
        AuthService service = CreateService();
        service.CurrentAuth = new Auth
        {
            Cookie = "auth_id=123; other=1; sess=abc"
        };

        service.ValidateCookieString();

        Assert.Equal("auth_id=123; sess=abc;", service.CurrentAuth.Cookie);
        Assert.True(File.Exists("auth.json"));
        string json = File.ReadAllText("auth.json");
        Auth? saved = JsonConvert.DeserializeObject<Auth>(json);
        Assert.NotNull(saved);
        Assert.Equal("auth_id=123; sess=abc;", saved.Cookie);
    }

    [Fact]
    public void Logout_DeletesAuthAndChromeData()
    {
        using TempFolder temp = new();
        using CurrentDirectoryScope _ = new(temp.Path);
        AuthService service = CreateService();
        Directory.CreateDirectory("chrome-data");
        File.WriteAllText("chrome-data/test.txt", "x");
        File.WriteAllText("auth.json", "{}");

        service.Logout();

        Assert.False(Directory.Exists("chrome-data"));
        Assert.False(File.Exists("auth.json"));
    }

    private static AuthService CreateService() =>
        new(new ServiceCollection().BuildServiceProvider());
}
