using System.IO;
using System.Text.Json;
using NexusShell.Models;

namespace NexusShell.Services;

public sealed class NexusPhotosFavoritesService
{
    private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };

    private readonly string _favoritesPath;
    private HashSet<string> _favoritePaths = new(StringComparer.OrdinalIgnoreCase);

    public NexusPhotosFavoritesService()
    {
        var root = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "NinjaNexus",
            "photos");
        Directory.CreateDirectory(root);
        _favoritesPath = Path.Combine(root, "favorites.json");
        Load();
    }

    public string FavoritesPath => _favoritesPath;

    public event EventHandler? FavoritesChanged;

    public bool IsFavorite(string fullPath) =>
        !string.IsNullOrWhiteSpace(fullPath) && _favoritePaths.Contains(fullPath);

    public void ApplyFavorites(IReadOnlyList<NexusPhotoItem> photos)
    {
        foreach (var photo in photos)
        {
            photo.IsFavorite = IsFavorite(photo.FullPath);
        }
    }

    public void ToggleFavorite(NexusPhotoItem photo)
    {
        if (_favoritePaths.Contains(photo.FullPath))
        {
            _favoritePaths.Remove(photo.FullPath);
            photo.IsFavorite = false;
        }
        else
        {
            _favoritePaths.Add(photo.FullPath);
            photo.IsFavorite = true;
        }

        Save();
        FavoritesChanged?.Invoke(this, EventArgs.Empty);
    }

    public IReadOnlyList<string> GetFavoritePaths() => _favoritePaths.ToList();

    private void Load()
    {
        if (!File.Exists(_favoritesPath))
        {
            return;
        }

        try
        {
            var json = File.ReadAllText(_favoritesPath);
            var paths = JsonSerializer.Deserialize<List<string>>(json) ?? [];
            _favoritePaths = new HashSet<string>(paths, StringComparer.OrdinalIgnoreCase);
        }
        catch
        {
            _favoritePaths = new(StringComparer.OrdinalIgnoreCase);
        }
    }

    private void Save()
    {
        var json = JsonSerializer.Serialize(_favoritePaths.OrderBy(static p => p).ToList(), JsonOptions);
        File.WriteAllText(_favoritesPath, json);
    }
}
