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 LabOrderValueService : ILabOrderValueService
    {
        /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

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

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

            var query = $@"SELECT COUNT(*) OVER () AS ""TotalItems"", LOV.""LabOrderValueId"", LOV.""OrderCode"", LOV.""Code"", LOV.""Name"", LOV.""Test"", LOV.""CreatedDate"", 
                                LOV.""CreatedBy"", LO.""LabOrderId"" ,LO.""Name"" AS ""LabOrderName""  FROM ""LabOrderValue"" LOV
                                JOIN ""LabOrder"" LO ON LO.""LabOrderId"" = LOV.""LabOrderId""
                                {where} Order by ""LabOrderValueId"" DESC";

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

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

        /// <inheritdoc />
        public async Task<int> AddAsync(LabOrderValueModel model)
        {
            var checkIf = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""LabOrderValueId"") FROM ""LabOrderValue"" WHERE ""OrderCode"" = '{model.OrderCode.Trim()}' AND ""LabOrderValueId"" <> {model.LabOrderValueId}");
            if (checkIf > 0)
            {
                return -1;
            }

            var labOrderValue = new LabOrderValue
            {
                OrderCode = model.OrderCode,
                Name = model.Name,
                Code = model.Code,
                LabOrderId = model.LabOrderId,
                CreatedBy = model.CreatedBy,
                CreatedDate = DateTime.UtcNow
            };

            return await this.unitOfWork.LabOrderValues.InsertAsync(labOrderValue);
        }

        /// <inheritdoc />
        public async Task<int> UpdateAsync(LabOrderValueModel model)
        {
            var checkIf = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""LabOrderValueId"") FROM ""LabOrderValue"" WHERE ""OrderCode"" = '{model.OrderCode}' AND ""LabOrderValueId"" <> {model.LabOrderValueId}");
            if (checkIf > 0)
            {
                return -1;
            }

            var labOrderValue = await this.unitOfWork.LabOrderValues.FindAsync(m => m.LabOrderValueId == model.LabOrderValueId);
            labOrderValue.LabOrderValueId = model.LabOrderValueId;
            labOrderValue.OrderCode = model.OrderCode?.Trim();
            labOrderValue.Name = model.Name;
            labOrderValue.Code = model.Code;
            labOrderValue.LabOrderId = model.LabOrderId;
            labOrderValue.ModifiedBy = model.ModifiedBy;
            labOrderValue.ModifiedDate = DateTime.UtcNow;

            return await this.unitOfWork.LabOrderValues.UpdateAsync(labOrderValue);
        }

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

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