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 Shared.UserModels.Filters;
    using Utilities;

    /// <inheritdoc />
    [Authorize]
    [Route("api/encounter-type")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class EncounterTypeController : BaseController
    {
        /// <summary>
        /// The coupon services.
        /// </summary>
        private readonly IEncounterTypeService encounterTypeService;

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

        /// <inheritdoc />
        public EncounterTypeController(IEncounterTypeService encounterTypeService, IAuditLogService auditLogServices)
        {
            this.encounterTypeService = encounterTypeService;
            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<EncounterTypeModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody]EncounterTypeFilterModel model)
        {
            model = (EncounterTypeFilterModel)EmptyFilter.Handler(model);
            var encounter = await this.encounterTypeService.FetchAsync(model);
            return encounter == null ? this.ServerError() : this.Success(encounter);
        }
      

        /// <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 - Encounter added successfully.
        /// - 409 - Encounter 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] EncounterTypeModel model,[FromHeader] LocationHeader header)
        {
            model = (EncounterTypeModel)EmptyFilter.Handler(model);
            model.LocationId = Convert.ToInt32(header.LocationId);
            var response = await this.encounterTypeService.AddAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given Encounter Type has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

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

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

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

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

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

        /// <summary>
        /// The delete encounter type.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - encounter type deleted successfully.
        /// - 409 - encounter type 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] EncounterTypeModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (EncounterTypeModel)EmptyFilter.Handler(model);
                model.LocationId = Convert.ToInt32(header.LocationId);
                var chargeName = await this.encounterTypeService.FindNameByEncounterTypeId(model.EncounterTypeId);
                var response = await this.encounterTypeService.DeleteAsync(model.EncounterTypeId);
                if (response == 0)
                {
                    return this.ServerError();
                }

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

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

                return this.ServerError();
            }
        }

    }
}