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

    // ReSharper disable StyleCop.SA1126

    /// <inheritdoc />
    /// <summary>
    /// The account controller.
    /// </summary>
    [Authorize]
    [Route("api/provider-medication")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class ProviderMedicationController : BaseController
    {
        /// <summary>
        /// The provider medication service.
        /// </summary>
        private readonly IProviderMedicationService providerMedicationService;

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

        /// <inheritdoc />
        public ProviderMedicationController(IProviderMedicationService providerMedicationService, IAuditLogService auditLogServices)
        {
            this.providerMedicationService = providerMedicationService;
            this.auditLogServices = auditLogServices;
        }

        /// <summary>
        /// Adds the provider medication in bulk asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("add-provider-medication-bulk")]
        public async Task<ActionResult> AddProviderMedicationInBulkAsync([FromBody] ProviderMedicationGroupModel model, [FromHeader] LocationHeader header)
        {
            model = (ProviderMedicationGroupModel)EmptyFilter.Handler(model);
            var response = await this.providerMedicationService.AddProviderMedicationInBulk(model);
            if (response > 0)
            {
                try
                {
                    var auditLog = new AuditLogModel
                    {
                        AccountId = model.CreatedBy,
                        LogTypeId = (int)LogTypes.ProviderMedication,
                        LogDate = DateTime.Now,
                        LogFrom = (short)model.LoginRoleId,
                        LogDescription = $"<b>{model.CreatedByName}</b> has added Provider Medication of <strong>{model.TagName}</strong> successfully.",
                        LocationId = Convert.ToInt32(header.LocationId)
                    };
                    await this.auditLogServices.LogAsync(auditLog);
                }
                catch(Exception ex)
                {

                }
               
            }

            return this.Success(response);
        }

        /// <summary>
        /// Fetches all medication list asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("fetch-all-provider-medication")]
        public async Task<ActionResult> FetchAllMedicationListAsync([FromBody] ProviderMedicationMasterModel model)
        {
            model ??=new ProviderMedicationMasterModel();
            var response = await this.providerMedicationService.FetchAddedMedicationAsync(model);
            return this.Success(response);
        }

        /// <summary>
        /// Fetches all tag name asynchronous.
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("get-all-tag-name")]
        public async Task<ActionResult> FetchAllTagNameAsync()
        {
            return this.Success(await this.providerMedicationService.GetAllTagsAsync());
        }
        
        /// <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>
        //[HttpPut]
        //[Route("update")]
        //[ProducesResponseType(typeof(string), 200)]
        //[ProducesResponseType(409)]
        //[ProducesResponseType(500)]
        //public async Task<ActionResult> UpdateAsync([FromBody] ProviderMedicationMasterModel model)
        //{
        //    model = (ProviderMedicationMasterModel)EmptyFilter.Handler(model);
        //    var response = await this.providerMedicationService.UpdateAsync(model);
        //    switch (response)
        //    {
        //        case -1:
        //            return this.Conflict("Given Product 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 Visit Type - {model.VisitorName} on { DateTime.UtcNow.AddMinutes(330) }"
        //    //};
        //    //await this.auditLogServices.LogAsync(auditLogModel);

        //    return this.Success("Product 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] ProviderMedicationMasterModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (ProviderMedicationMasterModel)EmptyFilter.Handler(model);
                //var visitorName = await this.providerMedicationService.FindNameByVisitorId(model.ProviderMedicationMasterId);
                var response = await this.providerMedicationService.DeleteAsync(model.ProviderMedicationMasterId);
                if (response == 0)
                {
                    return this.ServerError();
                }

                var auditLogModel = new AuditLogModel
                { 
                   AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.ProviderMedication,
                  LogFrom = (int)AccountType.Administrator,
                   LogDate = DateTime.UtcNow.AddMinutes(330),
                  LogDescription = $" { model.ModifiedByName } has deleted Product Type - {model.TagName} on { DateTime.UtcNow.AddMinutes(330) }"
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                return this.Success("Product has been deleted successfully.");
            }
            catch (NpgsqlException exception)
            {
                if (exception.Message.Contains("violates foreign key constraint"))
                {
                    return this.Conflict("Product already in use can't be deleted.");
                }

                return this.ServerError();
            }
        }
    }
}