using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NexusReader.Application.Abstractions.Persistence;
using NexusReader.Data.Persistence;

namespace NexusReader.Infrastructure.Persistence;

/// <summary>
/// EF Core implementation of <see cref="IUserLibraryStore"/> using <see cref="AppDbContext"/>.
/// </summary>
internal sealed class UserLibraryStore : IUserLibraryStore
{
    private readonly AppDbContext _context;

    public UserLibraryStore(AppDbContext context)
    {
        _context = context;
    }

    /// <inheritdoc />
    public async Task<List<Guid>> GetOwnedBookIdsAsync(string userId, CancellationToken cancellationToken = default)
    {
        return await _context.Ebooks
            .Where(e => e.UserId == userId)
            .Select(e => e.Id)
            .ToListAsync(cancellationToken);
    }

    /// <inheritdoc />
    public async Task<Dictionary<Guid, string>> GetBookTitlesAsync(List<Guid> bookIds, CancellationToken cancellationToken = default)
    {
        if (bookIds == null || !bookIds.Any())
        {
            return new Dictionary<Guid, string>();
        }

        return await _context.Ebooks
            .Where(e => bookIds.Contains(e.Id))
            .ToDictionaryAsync(e => e.Id, e => e.Title, cancellationToken);
    }
}
