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

    /// <inheritdoc />
    [Authorize]
    [Route("api/countries")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class CountriesController : BaseController
    {
        /// <summary>
        /// The country services.
        /// </summary>
        private readonly ICountryService countriesServices;

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

        /// <inheritdoc />
        public CountriesController(ICountryService countriesServices, IAuditLogService auditLogServices)
        {
            this.countriesServices = countriesServices;
            this.auditLogServices = auditLogServices;
        }

        /// <summary>
        /// The fetch countries.
        /// </summary>
        /// <param name="model">
        /// The country filter model.
        /// </param>
        /// <returns>
        /// The list of countries.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - List of countries.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("fetch")]
        [ProducesResponseType(typeof(List<CountryModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody]CountryFilterModel model)
        {
            model = (CountryFilterModel)EmptyFilter.Handler(model);
            var countries = await this.countriesServices.FetchAsync(model);
            return countries == null ? this.ServerError() : this.Success(countries);
        }

        /// <summary>
        /// The add country.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Country added successfully.
        /// - 409 - Country 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]CountryModel model,[FromHeader] LocationHeader header)
        {
            model = (CountryModel)EmptyFilter.Handler(model);
            
            var response = await this.countriesServices.AddAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given country name has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.Countries,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow,
                LogDescription = $"{model.CountryName} ({model.CountryCode}) country has been added.",
                LocationId= Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

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

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

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.Countries,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow,
                LogDescription = $"{model.CountryName} ({model.CountryCode}) country has been updated.",
                LocationId= Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

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

        /// <summary>
        /// The delete country.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Country deleted successfully.
        /// - 409 - Country can not be deleted.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpDelete]
        [Route("delete")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> DeleteAsync([FromBody]CountryModel model,[FromHeader]LocationHeader header)
        {
            try
            {
                model = (CountryModel)EmptyFilter.Handler(model);
                var response = await this.countriesServices.DeleteAsync(model.CountryId);
                if (response == 0)
                {
                    return this.ServerError();
                }

                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.Countries,
                    LogFrom = (int)AccountType.Administrator,
                    LogDate = DateTime.UtcNow,
                    LogDescription = $"{model.CountryName} ({model.CountryCode}) country has been deleted.",
                    LocationId = Convert.ToInt32(header.LocationId)
                };
                await this.auditLogServices.LogAsync(auditLogModel);

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

                return this.ServerError();
            }
        }

        /// <summary>
        /// The modify status of country.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Country status updated successfully.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPut]
        [Route("modify-status")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyStatusAsync([FromBody]CountryModel model,[FromHeader]LocationHeader header)
        {
            model = (CountryModel)EmptyFilter.Handler(model);
            var response = await this.countriesServices.ModifyStatusAsync(model.CountryId, Convert.ToInt32(model.ModifiedBy), model.Active);
            if (response == 0)
            {
                return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.Countries,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow,
                LogDescription = $"{model.CountryName} ({model.CountryCode}) country status has been updated to {(model.Active ? "'Active'" : "'Inactive'")}.",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success("Country status has been updated successfully.");
        }
    }
}