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.Common;
    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/visitors")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class VisitTypeController : BaseController
    {
        /// <summary>
        /// The coupon services.
        /// </summary>
        private readonly IVisitTypeService visitTypeService;

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

        /// <inheritdoc />
        public VisitTypeController(IVisitTypeService visitTypeService, IAuditLogService auditLogServices)
        {
            this.visitTypeService = visitTypeService;
            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<VisitTypeModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody] VisitTypeFilterModel model)
        {
            try
            {
                model = (VisitTypeFilterModel)EmptyFilter.Handler(model);
                var visitors = await this.visitTypeService.FetchAsync(model);
                return visitors == null ? this.ServerError() : this.Success(visitors);

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

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

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

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

            return this.Success("Visit 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] VisitTypeModel model,[FromHeader] LocationHeader header)
        {
            try
            {
                model = (VisitTypeModel)EmptyFilter.Handler(model);
                var visitorName = await this.visitTypeService.FindNameByVisitorId(model.VisitTypeId);
                var response = await this.visitTypeService.DeleteAsync(model.VisitTypeId);
                if (response == 0)
                {
                    return this.ServerError();
                }

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

                return this.Success(new GenericResponse
                {
                    Status = response > 0 ? GenericStatus.Success : GenericStatus.Warning
                });
            }
            catch (NpgsqlException exception)
            {
                if (exception.Message.Contains("violates foreign key constraint"))
                {
                    return this.Success(new GenericResponse
                    {
                        Status = GenericStatus.Error,
                        Message = exception.Message
                    });
                }

                throw;
            }
        }


        /// <summary>
        /// The delete charge type.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - charge type deleted successfully.
        /// - 409 - charge type can not be deleted.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("modify-status")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyStatusAsync([FromBody] VisitTypeModel model, [FromHeader] LocationHeader header)
        {

            model = (VisitTypeModel)EmptyFilter.Handler(model);

            var response = await this.visitTypeService.ModifyStatusAsync(model);
            if (response == 0)
            {
                return this.ServerError();
            }

            var auditLog = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.ChargeTypes,
                LogDate = DateTime.Now,
                LogFrom = (short)model.LoginRoleId,
                LogDescription = $"{model.CreatedByName} has modified<b>Visit Type</b> of <strong>{model.VisitorName}</strong> successfully.",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLog);

            return this.Success("Visit Type has been updated the status.");
        }
    }
}