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

    /// <inheritdoc />
    public class EncounterTypeService : IEncounterTypeService
    {
        /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        /// <inheritdoc cref="IEncounterTypeService" />
        public EncounterTypeService(IUnitOfWork unitOfWork) => this.unitOfWork = unitOfWork;

        /// <inheritdoc />
        public Task<IEnumerable<EncounterTypeModel>> FetchAsync(EncounterTypeFilterModel model)
        {
            var where = " WHERE 1 = 1 ";
            if (!string.IsNullOrEmpty(model.EncounterName))
            {
                where += $@" AND TRIM(UPPER(""EncounterName"")) = '{model.EncounterName.Trim().ToUpper()}'";
            }

            if (model.Active != null)
            {
                where += $@" AND ""Active"" IS {((bool)model.Active ? "TRUE" : "FALSE")}";
            }

            var query = $@"SELECT COUNT(*) OVER () AS ""TotalItems"", * FROM ""EncounterType"" {where} Order by ""EncounterTypeId"" DESC";

            if (model.PageIndex <= 0)
            {
                return this.unitOfWork.Current.QueryAsync<EncounterTypeModel>(query);
            }

            model.PageIndex -= 1;
            query += " LIMIT " + model.PageSize + " offset " + (model.PageIndex * model.PageSize);
            return this.unitOfWork.Current.QueryAsync<EncounterTypeModel>(query);
        }
     

        /// <inheritdoc />
        public async Task<int> AddAsync(EncounterTypeModel model)
        {
            try
            {
                var checkIf = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""EncounterTypeId"") FROM ""EncounterType"" WHERE TRIM(UPPER(""EncounterName"")) = '{model.EncounterName.ToUpper().Trim()}'");
                if (checkIf > 0)
                {
                    return -1;
                }

                var encounterType = new EncounterType
                {
                    Active = true,    
                    EncounterName = model.EncounterName,
                    CreatedBy = model.CreatedBy,
                    CreatedDate = DateTime.Now,
                };

                return await this.unitOfWork.EncounterType.InsertAsync(encounterType);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
            }

            return 0;
        }       

        /// <inheritdoc />
        public async Task<int> UpdateAsync(EncounterTypeModel model)
        {
            var checkIf = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""EncounterTypeId"") FROM ""EncounterType"" WHERE TRIM(UPPER(""EncounterName"")) = '{model.EncounterName.ToUpper().Trim()}' AND ""EncounterTypeId"" <> {model.EncounterTypeId}");
            if (checkIf > 0)
            {
                return -1;
            }

            var encounterType = await this.unitOfWork.EncounterType.FindAsync(m => m.EncounterTypeId == model.EncounterTypeId);
            encounterType.EncounterName = model.EncounterName;
            encounterType.Active = true;
            encounterType.ModifiedBy = model.ModifiedBy;
            encounterType.ModifiedDate = DateTime.Now;
            return await this.unitOfWork.EncounterType.UpdateAsync(encounterType);
        }

        /// <inheritdoc />
        public Task<int> DeleteAsync(int chargeTypesId)
        {
            var query = $@"DELETE FROM ""EncounterType"" WHERE ""EncounterTypeId""= {chargeTypesId}";
            return this.unitOfWork.Current.ExecuteAsync(query);
        }

        public async Task<string> FindNameByEncounterTypeId(int chargeTypesId)
        {
            var query = $@"SELECT ""EncounterName"" FROM ""EncounterType"" WHERE ""EncounterTypeId"" = {chargeTypesId}";
            var response = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<string>(query);
            return response;
        }

    }
}