using Dapper;

namespace Hims.Infrastructure.Services
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Hims.Domain.Entities;
    using Hims.Domain.Repositories.UnitOfWork;
    using Hims.Domain.Services;
    using Hims.Domain.Entities.Enums;
    using Hims.Shared.UserModels.GataPass;
    using Hims.Shared.UserModels.Slots;
    using Resource = Hims.Shared.UserModels.Discharge.Resource;

    /// <summary> The chat service.</summary>
    public class GatePassService : IGatePassService
    {
        /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        /// <inheritdoc cref="IChatService" />
        public GatePassService(IUnitOfWork unitOfWork) => this.unitOfWork = unitOfWork;


        public async Task<int> InsertAsync(InsertModel model)
        {
            var record = new GatePass
            {
                ValidUpto=model.ValidUpto,
                Remark=model.Remark,
                AdmissionId = model.AdmissionId,
                CreatedBy = model.CreatedBy,
                CreatedDate = model.CreatedDate,
                TypeId= model.TypeId > 1 ?(int)GatePassType.Final:(int)GatePassType.Provisional

            };

            var response = await this.unitOfWork.GatePass.InsertAsync(record);
            return response;
        }

        public async Task<int> UpdateAsync(InsertModel model)
        {
            var record = await this.unitOfWork.GatePass.FindAsync(x => x.GatePassId == Convert.ToInt32(model.Id));

            record.ModifiedBy = model.ModifiedBy;
            record.ModifiedDate = model.ModifiedDate;
            record.ValidUpto= model.ValidUpto;
            record.Remark = model.Remark;
           
            var response = await this.unitOfWork.GatePass.UpdateAsync(record);
            return response;
        }

        public async Task<InsertModel> FetchAsync(InsertModel model)
        {

            var where = $@"where AD.""AdmissionId"" = {Convert.ToInt32(model.Id)}";
            if (model.TypeId != null)
            {
                where += $@" and  GP.""TypeId"" = {model.TypeId} ";
            }
            var query = $@"Select GP.*, A.""FullName"" as ""CreatedByName"",P.""Zipcode"",P.""City"",P.""StreetAddress"" as ""Area"",CT.""CaseTypeName""
                        from ""GatePass"" GP
                        join ""Account"" A on A.""AccountId""=GP.""CreatedBy""
                        join ""Admission"" AD on AD.""AdmissionId""=GP.""AdmissionId""
                        join ""Patient"" P on P.""PatientId""=AD.""PatientId""
                        left join ""CaseType"" CT on CT.""CaseTypeId"" = AD.""CaseTypeId""
                        {where}";

            var record = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<InsertModel>(query);
            return record;
        }      

    }
}
