namespace Hims.Infrastructure.Services
{
    using System.Threading.Tasks;
    using Dapper;
    using Hims.Domain.Entities;
    using Hims.Domain.Repositories.UnitOfWork;
    using Hims.Domain.Services;
    using Hims.Shared.EntityModels;

    /// <summary>
    /// The message service.
    /// </summary>
    public class MessageService : IMessageService
    {
        /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        /// <inheritdoc cref="IIconService" />
        public MessageService(IUnitOfWork unitOfWork) => this.unitOfWork = unitOfWork;

        /// <inheritdoc />
        public async Task<int> CreateMessageAsync(MessageModel model)
        {
            var message = new Message
            {
                Active = true,
                AppointmentId = model.AppointmentId,
                Messages = model.Messages,
                PatientId = model.PatientId,
                ProviderId = model.ProviderId,
                DoctorMessageCount = model.DoctorMessageCount,
                PatientMessageCount = model.PatientMessageCount
            };
            return await this.unitOfWork.Message.InsertAsync(message);
        }

        /// <inheritdoc />
        public async Task<MessageModel> FetchMessagesAsync(int appointmentId)
        {
            var query = $@"SELECT ""MessageId"", ""AppointmentId"", ""ProviderId"", ""PatientId"", ""Messages"", ""DoctorMessageCount"",""PatientMessageCount"",""Active""
	                              FROM ""Message"" where ""AppointmentId"" = {appointmentId}";
            return await this.unitOfWork.Current.QueryFirstOrDefaultAsync<MessageModel>(query);
        }

        /// <inheritdoc />
        public async Task<int> UpdateMessageAsync(MessageModel model)
        {
            var message = new Message
            {
                MessageId = model.MessageId,
                Messages = model.Messages,
                DoctorMessageCount = model.DoctorMessageCount,
                PatientMessageCount = model.PatientMessageCount
            };
            return await this.unitOfWork.Message.UpdateAsync(message);
        }

        /// <inheritdoc />
        public async Task<int> ChangeReadStatus(long messageId, string from)
        {
            var query = $@"Update ""Message"" set ""DoctorMessageCount""= null where ""MessageId"" = {messageId}  ";
            if (from == "Patient")
            {
                query = $@"Update ""Message"" set ""PatientMessageCount""= null where ""MessageId"" = {messageId}  ";
            }

            return await this.unitOfWork.Current.ExecuteAsync(query);
        }
    }
}
