using System;

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 LanguageServices : ILanguageService
    {
        /// <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 LanguageServices(IUnitOfWork unitOfWork) => this.unitOfWork = unitOfWork;

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

            var query = $@"SELECT COUNT(*) OVER () AS ""TotalItems"", ""LanguageId"", ""Name"", ""CreatedDate"", ""CreatedBy"",""Active"" FROM ""Language"" {where} Order by ""LanguageId"" DESC";

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

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

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

            var language = new Language
            {
                Name = model.Name?.Trim(),
                CreatedBy = model.CreatedBy,
                CreatedDate = DateTime.UtcNow
            };

            return await this.unitOfWork.Languages.InsertAsync(language);
        }

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

            var language = await this.unitOfWork.Languages.FindAsync(m => m.LanguageId == model.LanguageId);
            language.Name = model.Name?.Trim();
            language.ModifiedBy = model.ModifiedBy;
            language.ModifiedDate = DateTime.UtcNow;

            return await this.unitOfWork.Languages.UpdateAsync(language);
        }

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