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

namespace Hims.Infrastructure.Services
{
    public class ContactDetailsServices : IContactDetailsService
    {
        /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        /// <inheritdoc cref="IBedService" />   
        public ContactDetailsServices(IUnitOfWork unitOfWork) => this.unitOfWork = unitOfWork;
        public async Task<int> AddAsync(ContactDetails model)
        {
            var checkIf = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""PatientId"") FROM ""ContactDetails"" WHERE ""PatientId"" = '{model.PatientId}'");
            if (checkIf > 0)
            {
                return -1;
            }
            string inputData = model.Details;

            if (!string.IsNullOrEmpty(inputData))
            {
                var problem = new ContactDetails
                {
                    IsActive = true,
                    Details = model.Details,
                    PatientId = model.PatientId,
                    Type = model.Type,
                    CreatedBy = model.CreatedBy,
                    CreatedDate = DateTime.Now,
                };

                return await this.unitOfWork.contactDetailss.InsertAsync(problem);
            }
            else { return -1; }

            
        }

        public Task<int> DeleteAsync(int Id)
        {
            var query = $@"DELETE FROM ""ContactDetails"" WHERE ""Id""= {Id}";
            return this.unitOfWork.Current.ExecuteAsync(query);
        }

        public async Task<IEnumerable<ContactDetails>> FetchAsync(ContactDetails model)
        {
            var query = $@"SELECT * FROM ""ContactDetails""";
            var response = await this.unitOfWork.Current.QueryAsync<ContactDetails>(query);
            return response;
        }

        public async Task<IEnumerable<ContactDetails>> FindById(int PatientId)
        {
            var query = $@"SELECT * FROM ""ContactDetails"" WHERE ""PatientId""= {PatientId}";
            var response = await this.unitOfWork.Current.QueryAsync<ContactDetails>(query);
            return response;
        }
    

        public async Task<int> UpdateAsync(ContactDetails model)
        {
            var problems = await this.unitOfWork.contactDetailss.FindAsync(m => m.Id == model.Id);
            if (model.Details != "") { problems.Details = model.Details; }
            problems.ModifiedBy = model.ModifiedBy;
            problems.ModifiedDate = DateTime.Now;
            return await this.unitOfWork.contactDetailss.UpdateAsync(problems);
        }
    }
}
