
using System.Security.Claims;
using Bit.Core.Exceptions;
using Bit.Core.Services;
using Bit.Core.Tools.Entities;
using Bit.Core.Tools.Repositories;
using Bit.Core.Tools.SendFeatures.Queries.Interfaces;

namespace Bit.Core.Tools.SendFeatures.Queries;

/// <inheritdoc cref="ISendOwnerQuery"/>
public class SendOwnerQuery : ISendOwnerQuery
{
    private readonly ISendRepository _repository;
    private readonly IUserService _users;

    /// <summary>
    /// Instantiates the command
    /// </summary>
    /// <param name="sendRepository">
    /// Retrieves send records
    /// </param>
    /// <exception cref="ArgumentNullException">
    /// Thrown when <paramref name="sendRepository"/> is <see langword="null"/>.
    /// </exception>
    public SendOwnerQuery(ISendRepository sendRepository, IUserService users)
    {
        _repository = sendRepository;
        _users = users ?? throw new ArgumentNullException(nameof(users));
    }

    /// <inheritdoc cref="ISendOwnerQuery.Get"/>
    public async Task<Send> Get(Guid id, ClaimsPrincipal user)
    {
        var userId = _users.GetProperUserId(user) ?? throw new BadRequestException("invalid user.");
        var send = await _repository.GetByIdAsync(id);

        if (send == null || send.UserId != userId)
        {
            throw new NotFoundException();
        }

        return send;
    }

    /// <inheritdoc cref="ISendOwnerQuery.GetOwned"/>
    public async Task<ICollection<Send>> GetOwned(ClaimsPrincipal user)
    {
        var userId = _users.GetProperUserId(user) ?? throw new BadRequestException("invalid user.");
        var sends = await _repository.GetManyByUserIdAsync(userId);

        return sends;
    }
}
