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

    using Hims.Shared.UserModels.Filters;

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

        /// <summary>Initializes a new instance of the <see cref="IcdCodeServices"/> class.</summary>
        /// <param name="unitOfWork"> The unit of work.</param>
        public IcdCodeServices(IUnitOfWork unitOfWork) => this.unitOfWork = unitOfWork;

        /// <inheritdoc />
        public Task<IEnumerable<ICDCodeModel>> FetchAsync(IcdCodeFilterModel model)
        {
            var where = " WHERE 1 = 1 ";
            if (!string.IsNullOrEmpty(model.Code))
            {
                where += $@" AND ""Code"" ILIKE '%{model.Code}%'";
            }

            var query = $@"SELECT COUNT(*) OVER () AS ""TotalItems"", ""ICDCodeId"", ""Code"", ""Description"", ""CreatedDate"", ""CreatedBy"",""Active"" FROM ""ICDCode"" {where} Order by ""ICDCodeId"" DESC";

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

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

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

            var icdCode = new ICDCode
            {
                Code = model.Code?.Trim(),
                Description = model.Description
            };

            return await this.unitOfWork.ICDCodes.InsertAsync(icdCode);
        }

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

            var icdCode = await this.unitOfWork.ICDCodes.FindAsync(m => m.ICDCodeId == model.ICDCodeId);
            icdCode.Code = model.Code?.Trim();
            icdCode.Description = model.Description;

            return await this.unitOfWork.ICDCodes.UpdateAsync(icdCode);
        }

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

        /// <inheritdoc />
        public Task<int> updateProviderEncounterAsync(int icdCodeId)
        {
            var query = $@"UPDATE ""ProviderEncounter""   SET ""ICDIds"" = array_to_string(array_remove(string_to_array(""ICDIds"",','), '{icdCodeId}'),',') ";
            return this.unitOfWork.Current.ExecuteAsync(query);
        }
    }
}