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 Hims.Shared.UserModels.Filters;

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

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

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

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

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

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

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

            var problemList = new ProblemList
            {
                Name = model.Name.Trim(),
                Description = model.Description,
                CreatedBy = model.CreatedBy,
                CreatedDate = DateTime.UtcNow
            };

            return await this.unitOfWork.ProblemList.InsertAsync(problemList);
        }

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

            var problemList = await this.unitOfWork.ProblemList.FindAsync(m => m.ProblemListId == model.ProblemListId);
            problemList.Name = model.Name.Trim();
            problemList.Description = model.Description;
            problemList.ModifiedBy = model.ModifiedBy;
            problemList.ModifiedDate = DateTime.UtcNow;

            return await this.unitOfWork.ProblemList.UpdateAsync(problemList);
        }

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