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

    /// <inheritdoc />
    [Authorize]
    [Route("api/vital-type")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class VitalTypeController : BaseController
    {
        /// <summary>
        /// The vital type services.
        /// </summary>
        private readonly IVitalTypeService vitalTypeService;

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

        /// <inheritdoc />
        public VitalTypeController(IVitalTypeService vitalTypeService, IAuditLogService auditLogServices)
        {
            this.vitalTypeService = vitalTypeService;
            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] FilterModel model)
        {
            try
            {
                model = (FilterModel)EmptyFilter.Handler(model);
                var vitalType = await this.vitalTypeService.FetchAsync(model);
                return vitalType == null ? this.ServerError() : this.Success(vitalType);

            }
            catch (Exception ex)
            {

            }
            return default;
        }


        /// <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);
            var response = await this.vitalTypeService.AddAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given Vital Type has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

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

            return this.Success("Vital Type 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] UpdateModel model,[FromHeader] LocationHeader header)
        {
            model = (UpdateModel)EmptyFilter.Handler(model);
            var response = await this.vitalTypeService.UpdateAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given Vital Type has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

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

            return this.Success("Vital Type 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] DeleteModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (DeleteModel)EmptyFilter.Handler(model);
                var name = await this.vitalTypeService.FindNameByVitalTypeId(model.VitalTypeId);
                var response = await this.vitalTypeService.DeleteAsync(model);
                if (response == 0)
                {
                    return this.ServerError();
                }

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

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

                return this.ServerError();
            }
        }

        /// <summary>
        /// Fetches the unit type asynchronous.
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("fetch-unit-type")]
        public async Task<ActionResult> FetchUnitTypesAsync()
        {
            try
            {
                var response = await this.vitalTypeService.FetchUnitTypeAsync().ConfigureAwait(false);
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

    }
}