namespace Hims.Api.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Domain.Services;
    using Hims.Api.Models;
    using Hims.Domain.Helpers;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    
    using Npgsql;
    using Shared.DataFilters;
    using Shared.EntityModels;
    using Shared.Library.Enums;
    using Shared.UserModels.ProviderScheduleVisits;
    using Utilities;

    /// <inheritdoc />
    [Authorize]
    [Route("api/provider-schedule-visits")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class ProviderScheduleVisitsController : BaseController
    {
        /// <summary>
        /// The coupon services.
        /// </summary>
        private readonly IProviderScheduleVisitsService providerScheduleVisitsService;

        /// <summary>
        /// The audit log services.
        /// </summary>
        private readonly IAuditLogService auditLogServices;

        /// <summary>
        /// The AES helper.
        /// </summary>
        private readonly IAESHelper aesHelper;


        /// <inheritdoc />
        public ProviderScheduleVisitsController(IProviderScheduleVisitsService providerScheduleVisitsService, IAuditLogService auditLogServices, IAESHelper aesHelper)
        {
            this.providerScheduleVisitsService = providerScheduleVisitsService;
            this.auditLogServices = auditLogServices;
            this.aesHelper = aesHelper;
        }

        /// <summary>
        /// The fetch coupons.
        /// </summary>
        /// <param name="model">
        /// The coupon filter model.
        /// </param>
        /// <returns>
        /// The list of coupons.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - List of coupons.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("fetch")]
        [ProducesResponseType(typeof(List<ProviderAvailabilityVisitTypeModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody] FilterModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (FilterModel)EmptyFilter.Handler(model);

                if (model.ProviderId == 0 || model.ProviderId == null && !string.IsNullOrEmpty(model.EncryptedProviderId)) {
                    model.ProviderId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedProviderId));
                }
                //model.LocationId = Convert.ToInt32(header.LocationId);
                var providerScheduleCharges = await this.providerScheduleVisitsService.FetchAsync(model);
                return providerScheduleCharges == null ? this.ServerError() : this.Success(providerScheduleCharges);

            }
            catch (Exception e)
            {
                return this.ServerError();
            }

        }

        
        
        /// <summary>
        /// The fetch coupons.
        /// </summary>
        /// <param name="model">
        /// The coupon filter model.
        /// </param>
        /// <returns>
        /// The list of coupons.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - List of coupons.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("doctor-visit")]
        [ProducesResponseType(typeof(List<ProviderScheduleChargesModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchDoctorVisitAsync([FromBody] FilterModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (FilterModel)EmptyFilter.Handler(model);
                model.LocationId = Convert.ToInt32(header.LocationId);
                var providerScheduleCharges = await this.providerScheduleVisitsService.FetchDoctorVisitsAsync(model);
                return providerScheduleCharges == null ? this.ServerError() : this.Success(providerScheduleCharges);

            }
            catch (Exception e)
            {
                return this.ServerError();
            }

        }

        /// <summary>
        /// The add coupon.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Coupon added successfully.
        /// - 409 - Coupon already exist.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("add")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> AddAsync([FromBody] InsertModel model, [FromHeader] LocationHeader header)
        {
            model = (InsertModel)EmptyFilter.Handler(model);
            //model.LocationId = Convert.ToInt32(header.LocationId);
            var response = await this.providerScheduleVisitsService.AddAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given Provider Schedule has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.ProviderScheduleCharge,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = model.ProviderAvailabilityVisitTypeId == 0 ? $" <b>{model.ModifiedByName}</b> has added Provider Schedule. on {DateTime.UtcNow.AddMinutes(330)}" : $" <b>{model.ModifiedByName}</b> has added Provider Schedule. on {DateTime.UtcNow.AddMinutes(330)}",
                LocationId = Convert.ToInt32(header.LocationId)

            };
            await this.auditLogServices.LogAsync(auditLogModel);
            if (model.ProviderAvailabilityVisitTypeId == 0)
            {
                return this.Success("Provider Schedule Charges has been added successfully.");
            }
            else
            {
                return this.Success("Provider Schedule Charges has been Updated successfully.");
            }
        }

        /// <summary>
        /// The update coupon.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Coupon updated successfully.
        /// - 409 - Coupon already exist.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("update")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> UpdateAsync([FromBody] InsertModel model, [FromHeader] LocationHeader header)
        {

            model = (InsertModel)EmptyFilter.Handler(model);
            //model.LocationId = Convert.ToInt32(header.LocationId);
            var response = await this.providerScheduleVisitsService.UpdateAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("GivenProvider Schedule has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.VisitType,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $" {model.ModifiedByName} has updated Provider Schedule on {DateTime.UtcNow.AddMinutes(330)}",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success("Provider Schedule has been updated successfully.");
        }

        /// <summary>
        /// The delete specialization.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Specialization deleted successfully.
        /// - 409 - Specialization can not be deleted.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("delete")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> DeleteAsync([FromBody] VisitTypeModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (VisitTypeModel)EmptyFilter.Handler(model);
                var visitorName = await this.providerScheduleVisitsService.FindNameByVisitorId(model.VisitTypeId);
                var response = await this.providerScheduleVisitsService.DeleteAsync(model.VisitTypeId);
                if (response == 0)
                {
                    return this.ServerError();
                }

                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.VisitType,
                    LogFrom = (int)AccountType.Administrator,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    LogDescription = $" {model.ModifiedByName} has deleted Visit Type - {visitorName} on {DateTime.UtcNow.AddMinutes(330)}",
                    LocationId = Convert.ToInt32(header.LocationId)
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                return this.Success("Visit Type has been deleted successfully.");
            }
            catch (NpgsqlException exception)
            {
                if (exception.Message.Contains("violates foreign key constraint"))
                {
                    return this.Conflict("Visit Type can't be deleted. Please contact Administrator.");
                }

                return this.ServerError();
            }
        }

        /// <summary>
        /// Modifies the lab component status asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("modify-status")]
        public async Task<ActionResult> ModifyStatusAsync([FromBody] InsertModel model)
        {
            model = (InsertModel)EmptyFilter.Handler(model);

            var response = await this.providerScheduleVisitsService.ModifyStatusAsync(model);
            return this.Success(response);
        }

        [HttpPost]
        [Route("fetch-provider-specialization")]
        [ProducesResponseType(typeof(List<ProviderAvailabilityVisitTypeModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchProvidersWithSpecializationAsync([FromHeader] LocationHeader header)
        {
            try
            {
                int loc = Convert.ToInt32(header.LocationId);
                var providerScheduleCharges = await this.providerScheduleVisitsService.FetchProvidersWithSpecializationAsync(loc);
                return providerScheduleCharges == null ? this.ServerError() : this.Success(providerScheduleCharges);

            }
            catch (Exception e)
            {
                return this.ServerError();
            }

        }
    }
}