using System.Collections.Generic;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using FluentResults;
using MediatR;
using Microsoft.AspNetCore.Http;
using NexusReader.Application.Queries.Recommendations;
using NexusReader.UI.Shared.Services;

namespace NexusReader.Web.Services;

/// <summary>
/// Server-side implementation of <see cref="IRecommendationService"/> that executes
/// the MediatR query directly inside the Web Server's request context.
/// </summary>
public sealed class ServerRecommendationService : IRecommendationService
{
    private readonly IMediator _mediator;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public ServerRecommendationService(IMediator mediator, IHttpContextAccessor httpContextAccessor)
    {
        _mediator = mediator;
        _httpContextAccessor = httpContextAccessor;
    }

    public async Task<List<RecommendationDto>?> GetRecommendationsAsync(CancellationToken cancellationToken = default)
    {
        var httpContext = _httpContextAccessor.HttpContext;
        if (httpContext?.User == null)
        {
            return new List<RecommendationDto>();
        }

        var userId = httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return new List<RecommendationDto>();
        }

        var result = await _mediator.Send(new GetContextualRecommendationsQuery(userId), cancellationToken);
        if (result.IsSuccess && result.Value != null)
        {
            return result.Value.Recommendations;
        }

        return new List<RecommendationDto>();
    }
}
