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 Hims.Shared.UserModels.ConsultationType;
    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 Utilities;

    /// <inheritdoc />
    [Authorize]
    [Route("api/consultation-type")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class ConsultationTypeController : BaseController
    {
        /// <summary>
        /// The coupon services.
        /// </summary>
        private readonly IConsultationTypeService consultationTypeService;

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

        /// <inheritdoc />
        public ConsultationTypeController(IConsultationTypeService consultationTypeService, IAuditLogService auditLogServices)
        {
            this.consultationTypeService = consultationTypeService;
            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<ConsultationTypeModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody] FilterModel model)
        {
            try
            {
                model = (FilterModel)EmptyFilter.Handler(model);
                var providerScheduleCharges = await this.consultationTypeService.FetchAsync(model);
                return providerScheduleCharges == null ? this.ServerError() : this.Success(providerScheduleCharges);

            }
            catch (Exception)
            {
                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 = (int)(!string.IsNullOrEmpty(header.LocationId) ? int.Parse(header.LocationId) : (int?)null);
            var response = await this.consultationTypeService.AddAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given Consultation Type Name has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.ConsultationType,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = model.ConsultationTypeId == 0 ? $" <b>{ model.ModifiedByName }</b> has added Consultation Type Name - <b>{model.Name}</b>. on { DateTime.UtcNow.AddMinutes(330) }" : $" <b>{ model.ModifiedByName }</b> has added Consultation Type - <b>{model.Name}</b>. on { DateTime.UtcNow.AddMinutes(330) }",
                LocationId=model.LocationId

            };
            await this.auditLogServices.LogAsync(auditLogModel);
            if (model.ConsultationTypeId == 0)
            {
                return this.Success("Consultation Type Name has been added successfully.");
            }
            else
            {
                return this.Success("Consultation Type Name 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] ConsultationTypeModel model,[FromHeader]LocationHeader header)
        {
            try
            {
                model = (ConsultationTypeModel)EmptyFilter.Handler(model);
                model.LocationId = Convert.ToInt32(header.LocationId);
                var consultationName = await this.consultationTypeService.FindNameByConsultationTypeId(model.ConsultationTypeId);
                var response = await this.consultationTypeService.DeleteAsync(model.ConsultationTypeId);
                if (response == 0)
                {
                    return this.ServerError();
                }

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

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

                return this.ServerError();
            }
        }

    }
}