using Dapper;
using Hims.Domain.Entities;
using Hims.Domain.Repositories.UnitOfWork;
using Hims.Domain.Services;
using Hims.Shared.UserModels;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Hims.Infrastructure.Services
{
    public class WhatsAppTicketsService : IWhatsAppTicketsService
    {
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        /// <inheritdoc cref="IWardService" />
        public WhatsAppTicketsService(IUnitOfWork unitOfWork) => this.unitOfWork = unitOfWork;

        /// <inheritdoc/>
        public async Task<int> ChangeStatus(WhatsAppTicketsModel model)
        {
            var OldWhatsAppTicket = await this.unitOfWork.WhatsAppTickets.FindAsync(l => l.TicketId == model.TicketId);
            if (OldWhatsAppTicket == null)
            {
                return -3;
            }
            OldWhatsAppTicket.Solved = (bool)!model.Solved;
            OldWhatsAppTicket.ModifiedBy = model.ModifiedBy;
            OldWhatsAppTicket.ModifiedDate = DateTime.Now;
            return  await this.unitOfWork.WhatsAppTickets.UpdateAsync(OldWhatsAppTicket);

            
        }

        /// <inheritdoc/>
        public Task<IEnumerable<WhatsAppTicketsModel>> GetAllWhatsAppTickets(WhatsAppTicketsModel model)
        {
            string where = "where 1=1 ";

            if (!string.IsNullOrEmpty(model.Name))
            {
                where += $@" and lower(wt.""Name"") ilike '%{model.Name.ToLower()}%' ";
            }

            if (model.Solved != null)
            {
                where += $@" and wt.""Solved"" = {model.Solved}";
            }
            if(model.Mobile != null)
            {
                where += $@" and wt.""Mobile"" ilike '%{model.Mobile}%' ";
            }

            var Query = $@"select count(*) over () as ""TotalItems"", wt.""TicketId"",wt.""TicketNo"",wt.""Mobile"",wt.""Name"",
			   wt.""Regarding"", wt.""Solved"",wt.""CreatedDate"" , wt.""ModifiedBy"", B.""FullName"" as ""ModifiedByName"" , wt.""ModifiedDate"" From ""WhatsAppTickets"" wt
                 left join ""Account"" B on B.""AccountId"" = wt.""ModifiedBy""  {where}  Order by wt.""TicketId"" desc";

            if (model.PageSize != null && model.PageIndex != null)
            {
                model.PageIndex = model.PageIndex > 0 ? model.PageIndex - 1 : model.PageIndex;
                Query += $@" limit {model.PageSize} offset {model.PageIndex * model.PageSize}";
            }
            return this.unitOfWork.Current.QueryAsync<WhatsAppTicketsModel>(Query);
        }
    }
}
