using Microsoft.EntityFrameworkCore;
using NexusReader.Application.Abstractions.Persistence;
using NexusReader.Data.Persistence;
using NexusReader.Domain.Entities;

namespace NexusReader.Infrastructure.Persistence;

/// <summary>
/// EF Core implementation of <see cref="IConceptsMapReadRepository"/>.
/// Uses <see cref="IDbContextFactory{TContext}"/> for Blazor-safe scoped context creation.
/// </summary>
internal sealed class ConceptsMapReadRepository : IConceptsMapReadRepository
{
    private readonly IDbContextFactory<AppDbContext> _dbContextFactory;

    public ConceptsMapReadRepository(IDbContextFactory<AppDbContext> dbContextFactory)
    {
        _dbContextFactory = dbContextFactory;
    }

    /// <inheritdoc />
    public async Task<string?> GetLastReadPageIdAsync(string userId, CancellationToken cancellationToken = default)
    {
        await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);

        var user = await dbContext.Users
            .Where(u => u.Id == userId)
            .Select(u => new { u.LastReadPageId })
            .FirstOrDefaultAsync(cancellationToken);

        return user?.LastReadPageId;
    }

    /// <inheritdoc />
    public async Task<List<KnowledgeUnit>> GetKnowledgeUnitsForBookAsync(
        Guid bookId,
        string tenantId,
        CancellationToken cancellationToken = default)
    {
        await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);

        return await dbContext.KnowledgeUnits
            .Where(k => k.EbookId == bookId &&
                        (k.TenantId == tenantId || k.TenantId == "global" || string.IsNullOrEmpty(k.TenantId)))
            .OrderBy(k => k.CreatedAt)
            .ToListAsync(cancellationToken);
    }
}
