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/charge-types")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class ChargeTypesController : BaseController
    {
        /// <summary>
        /// The coupon services.
        /// </summary>
        private readonly IChargeTypesService chargeTypesService;

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

        /// <inheritdoc />
        public ChargeTypesController(IChargeTypesService chargeTypesService, IAuditLogService auditLogServices)
        {
            this.chargeTypesService = chargeTypesService;
            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<ChargeTypesModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody]ChargeTypesFilterModel model,[FromHeader] LocationHeader header)
        {
            model = (ChargeTypesFilterModel)EmptyFilter.Handler(model);
            model.LocationId = Convert.ToInt32(header.LocationId);
            var charge = await this.chargeTypesService.FetchAsync(model);
            return charge == null ? this.ServerError() : this.Success(charge);
        }
      

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

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

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

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

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

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

        /// <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("delete")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> DeleteAsync([FromBody] ChargeTypesModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (ChargeTypesModel)EmptyFilter.Handler(model);
                model.LocationId = Convert.ToInt32(header.LocationId);
                var chargeName = await this.chargeTypesService.FindNameByChargeId(model.ChargeTypesId);
                var response = await this.chargeTypesService.DeleteAsync(model.ChargeTypesId);
                if (response == 0)
                {
                    return this.ServerError();
                }

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

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

                return this.ServerError();
            }
        }


        /// <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] ChargeTypesModel model, [FromHeader] LocationHeader header)
        {

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

            var response = await this.chargeTypesService.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>Charge Type</b> of <strong>{model.ChargeName}</strong> successfully.",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLog);

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

    }

}