using MediatR;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Infrastructure.Data;
using Sledgemapper.Api.Models;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Sledgemapper.Api.Handlers
{
    public class StartNewSessionHandler : IRequestHandler<NewSessionCommand, bool>
    {
        private readonly IMediator _mediator;
        private readonly SledgemapperDbContext _dbcontext;

        public StartNewSessionHandler(IMediator mediator, SledgemapperDbContext dbcontext)
        {
            _mediator = mediator;
            _dbcontext = dbcontext;
        }

        public async Task<bool> Handle(NewSessionCommand notification, CancellationToken cancellationToken)
        {
            var campaign = _dbcontext.Campaigns.First(c => c.CampaignName == notification.Campaign && c.OwnerId == notification.UserId.ToString());

            _dbcontext.Sessions.Add(new Session
            {
                SessionName = notification.SessionName,
                OwnerUserId = notification.UserId,
                CampaignId = campaign.CampaignId

            });
            await _dbcontext.SaveChangesAsync();
            return true;
        }
    }
}
