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

    /// <inheritdoc />
    [Authorize]
    [Route("api/order-prescription")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class OrderPrescriptionController : BaseController
    {
        /// <summary>
        /// The coupon services.
        /// </summary>
        private readonly IOrderPrescriptionService orderPrescriptionService;

        /// <summary>
        /// The audit log services.
        /// </summary>
        private readonly IAuditLogService auditLogServices;
       
        /// <inheritdoc />
        public OrderPrescriptionController(IOrderPrescriptionService orderPrescriptionService, IAuditLogService auditLogServices)
        {
            this.orderPrescriptionService = orderPrescriptionService;
            this.auditLogServices = auditLogServices;          
        }

        /// <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<ViewModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody] ViewModel model)
        {
            model = (ViewModel)EmptyFilter.Handler(model);
            var response = await this.orderPrescriptionService.FetchAsync(model);
            return response == null ? this.ServerError() : this.Success(response);
        }
        
        /// <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-types")]
        [ProducesResponseType(typeof(List<ViewModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchTypesAsync([FromBody] ViewModel model)
        {
            model = (ViewModel)EmptyFilter.Handler(model);
            var response = await this.orderPrescriptionService.FetchTypesAsync(model);
            return response == null ? this.ServerError() : this.Success(response);
        }


        /// <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("order-Fetch")]
        [ProducesResponseType(typeof(List<WardModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchWardAsync([FromBody] ViewModel model)
        {
            model = (ViewModel)EmptyFilter.Handler(model);
            var response = await this.orderPrescriptionService.FetchOrderAsync(model);
            // return wards == null ? this.ServerError() : this.Success(wards);
            return Success(response);
        }


        /// <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] ViewModel model, [FromHeader] LocationHeader header)
        {
            model = (ViewModel)EmptyFilter.Handler(model);
            var response = await this.orderPrescriptionService.AddAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given ward code has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.OrderPrescription,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $"<b> { model.createdByName }</b> has added OrderPrescription -<b> {model.ValueName}</b> on { DateTime.UtcNow.AddMinutes(330) }",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success("Ward has been added 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>
        [HttpPut]
        [Route("update")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> UpdateAsync([FromBody] ViewModel model, [FromHeader] LocationHeader header)
        {
            model = (ViewModel)EmptyFilter.Handler(model);
            var response = await this.orderPrescriptionService.UpdateAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given Ward has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

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

            return this.Success("Ward 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] ViewModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (ViewModel)EmptyFilter.Handler(model);
                var wardName = await this.orderPrescriptionService.FindNameByValueId(model.ValueId);
                var response = await this.orderPrescriptionService.DeleteAsync(model.ValueId);
                if (response == 0)
                {
                    return this.ServerError();
                }

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

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

                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-order-master")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> AddOrderMaster([FromBody] OrderPrescriptionMasterModel model)
        {
            model = (OrderPrescriptionMasterModel)EmptyFilter.Handler(model);
            var response = await this.orderPrescriptionService.AddOrderMaster(model);
            return this.Success(response);
        }


        /// <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-order-master")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> UpdateOrderMaster([FromBody] OrderPrescriptionMasterModel model)
        {
            model = (OrderPrescriptionMasterModel)EmptyFilter.Handler(model);
            var response = await this.orderPrescriptionService.UpdateOrderMaster(model);
            return this.Success(response);
        }

        /// <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-order-master")]
        [ProducesResponseType(typeof(List<WardModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchOrderMaster([FromBody] OrderPrescriptionMasterModel model)
        {
            
            var response = await this.orderPrescriptionService.FetchOrderMaster(model);
            return Success(response);
        }
       

        /// <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-order-master")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> DeleteOrderMaster([FromBody] ViewModel model)
        {
            try
            {
                model = (ViewModel)EmptyFilter.Handler(model);
                var response = await this.orderPrescriptionService.DeleteOrderMaster(model.OrderPrescriptionMasterId);
                if (response == 0)
                {
                    return this.ServerError();
                }
                return this.Success("Order name has been deleted successfully.");
            }
            catch (NpgsqlException exception)
            {
                if (exception.Message.Contains("violates foreign key constraint"))
                {
                    return this.Conflict("Order name can't be deleted. Please contact Administrator.");
                }

                return this.ServerError();
            }
        }
        /// <summary>
        /// The Modify EncounterOrder Templates.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("modify-encounterOrderTemplates")]
        [ProducesResponseType(typeof(int), 200)]
        public async Task<ActionResult> ModifyEncounterOrderTemplates([FromBody] EncounterOrderTemplatesModel model)
        {
            var response = model.EncounterTemplateId;
            model = (EncounterOrderTemplatesModel)EmptyFilter.Handler(model);
            var data = response > 0 ? await this.orderPrescriptionService.UpdateEncounterOrderTemplates(model) : await this.orderPrescriptionService.AddEncounterOrderTemplates(model);
            return Ok(data);
        }

        /// <summary>
        /// The Get EncounterOrder Templates.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("fetch-encounterOrderTemplates")]
        [ProducesResponseType(typeof(IEnumerable<EncounterOrderTemplatesModel>), 200)]
        public async Task<ActionResult> GetEncounterOrderTemplates([FromBody] EncounterOrderTemplatesModel model)
        {
            var result = await this.orderPrescriptionService.GetEncounterOrderTemplates(model);
            return Ok(result);
        }

        /// <summary>
        /// The change encounter order template status.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("change-status-encounterOrderTemplates")]
        [ProducesResponseType(typeof(int), 200)]
        public async Task<ActionResult> ChangeEncounterOrderTemplateStatus([FromBody] EncounterOrderTemplatesModel model)
        {
            model = (EncounterOrderTemplatesModel)EmptyFilter.Handler(model);
            var data = await this.orderPrescriptionService.ChangeEncounterOrderTemplateStatus(model);
            return Ok(data);
        }


    }
}