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 Hims.Shared.UserModels;
    using Hims.Shared.UserModels.TemplateDesign.ComponentType;

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

        /// <inheritdoc cref="IComponentTypeService" />
        public ComponentTypeService(IUnitOfWork unitOfWork) => this.unitOfWork = unitOfWork;

        public Task<int> DeleteAsync(DeleteModel model)
        {
            throw new NotImplementedException();
        }

        public async Task<IEnumerable<FetchModel>> FetchAllAsync(FetchModel model)
        {
            var where = $@" ";
            var query = $@"Select count(ct.""ComponentTypeId"") over() as ""TotalItems"",ct.""ComponentTypeId"",ct.""Name"",ct.""SubName"" from ""template"".""ComponentType"" ct 
                            {where} order by ct.""ComponentTypeId"" desc";
            return await this.unitOfWork.Current.QueryAsync<FetchModel>(query);
        }

        public async Task<int> InsertAsync(InsertModel model)
        {
            var checkIf = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>($@"Select count(*) from ""template"".""ComponentType"" where lower(""Name"")='{model.Name.ToLower()}' or lower(""SubName"")='{model.SubName.ToLower()}'");

            if (checkIf > 0)
            {
                return -1;
            }
            var componentType = new ComponentType
            {
                Name = model.Name,
                SubName = model.SubName
            };
            return await this.unitOfWork.ComponentTypes.InsertAsync(componentType);
        }

        public async Task<int> UpdateAsync(UpdateModel model)
        {
            var checkIf = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>($@"Select count(*) from ""template"".""ComponentType"" where lower(""Name"")='{model.Name.ToLower()}' or lower(""SubName"") ='{model.SubName.ToLower()}' and ""ComponentTypeId"" <> {model.ComponentTypeId}");
            if (checkIf > 0)
            {
                return -1;
            }
            var record = await this.unitOfWork.ComponentTypes.FindAsync(x => x.ComponentTypeId == model.ComponentTypeId);
            if (record != null)
            {
                record.Name = model.Name;
                record.SubName = model.SubName;
            }
            return await this.unitOfWork.ComponentTypes.UpdateAsync(record);
        }
    }
}