namespace Hims.Api.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;

    using Domain.Services;
    using Hims.Api.Models;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Models.Provider;
    using Npgsql;
    using Shared.DataFilters;
    using Shared.EntityModels;
    using Shared.Library.Enums;
    using Shared.UserModels.Filters;
    using Utilities;

    /// <inheritdoc />
    [Authorize]
    [Route("api/services")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class ServicesController : BaseController
    {
        /// <summary>
        /// The service services.
        /// </summary>
        private readonly IServiceService servicesServices;

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

        /// <inheritdoc />
        public ServicesController(IServiceService servicesServices, IAuditLogService auditLogServices)
        {
            this.servicesServices = servicesServices;
            this.auditLogServices = auditLogServices;
        }

        /// <summary>
        /// The fetch services.
        /// </summary>
        /// <param name="model">
        /// The service filter model.
        /// </param>
        /// <returns>
        /// The list of services.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - List of services.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("fetch")]
        [ProducesResponseType(typeof(List<ServiceModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody] ServiceFilterModel model)
        {
            model = (ServiceFilterModel)EmptyFilter.Handler(model);
            var services = await this.servicesServices.FetchAsync(model);
            return services == null ? this.ServerError() : this.Success(services);
        }

        /// <summary>
        /// The add service.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Service added successfully.
        /// - 409 - Service 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] ServiceModel model, [FromHeader] LocationHeader header)
        {
            model = (ServiceModel)EmptyFilter.Handler(model);
            var response = await this.servicesServices.AddAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given Symptom name has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.Services,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow,
                LogDescription = $"{model.ServiceName} Symptom has been added.",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success("Symptom has been added successfully.");
        }

        /// <summary>
        /// The update service.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Service updated successfully.
        /// - 409 - Service 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] ServiceModel model, [FromHeader] LocationHeader header)
        {
            model = (ServiceModel)EmptyFilter.Handler(model);
            var response = await this.servicesServices.UpdateAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given service name has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.Services,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow,
                LogDescription = $"{model.ServiceName} service has been updated.",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

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

        /// <summary>
        /// The delete service.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Service deleted successfully.
        /// - 409 - Service 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] ServiceModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (ServiceModel)EmptyFilter.Handler(model);
                var response = await this.servicesServices.DeleteAsync(model.ServiceId);
                if (response == 0)
                {
                    return this.ServerError();
                }

                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.Services,
                    LogFrom = (int)AccountType.Administrator,
                    LogDate = DateTime.UtcNow,
                    LogDescription = $"{model.ServiceName} service has been deleted.",
                    LocationId = Convert.ToInt32(header.LocationId)
                };
                await this.auditLogServices.LogAsync(auditLogModel);

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

                return this.ServerError();
            }
        }

        /// <summary>
        /// The modify status of service.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Service status updated successfully.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPut]
        [Route("modify-status")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyStatusAsync([FromBody] ServiceModel model, [FromHeader] LocationHeader header)
        {
            model = (ServiceModel)EmptyFilter.Handler(model);
            var response = await this.servicesServices.ModifyStatusAsync(model.ServiceId, Convert.ToInt32(model.ModifiedBy), model.Active);
            if (response == 0)
            {
                return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.Services,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow,
                LogDescription = $"{model.ServiceName} service status has been updated to {(!model.Active ? "'Active'" : "'Inactive'")}.",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success("Service status has been updated successfully.");
        }

        /// <summary>
        /// To find provider
        /// </summary>
        /// <param name="model" >
        /// The provider find request Model.
        /// </param>
        /// <returns>
        /// The provider model.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Provider model.
        /// - 400 - Sorry! We don't have a provider in the system.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("find")]
        [ProducesResponseType(typeof(ServiceModel), 200)]
        [ProducesResponseType(typeof(string), 400)]
        [ProducesResponseType(500)]

        public async Task<ActionResult> FindAsync([FromBody] FindSymptomRequest model)
        {
            model = (FindSymptomRequest)EmptyFilter.Handler(model);
            var services = await this.servicesServices.FindAsync(model.ServiceId);
            return services == null ? this.ServerError() : this.Success(services);
        }
    }
}