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/insurance-companies")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class InsuranceCompaniesController : BaseController
    {
        /// <summary>
        /// The insuranceCompany services.
        /// </summary>
        private readonly IInsuranceCompanyService insuranceCompaniesServices;

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

        /// <inheritdoc />
        public InsuranceCompaniesController(IInsuranceCompanyService insuranceCompaniesServices, IAuditLogService auditLogServices)
        {
            this.insuranceCompaniesServices = insuranceCompaniesServices;
            this.auditLogServices = auditLogServices;
        }

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

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

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.InsuranceCompanies,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $"{model.ModifiedByName} has added {model.FullName} insurance company on {DateTime.UtcNow.AddMinutes(330)}" ,
                LocationId= Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);
            return this.Success("Insurance Company has been added successfully.");
        }

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

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.InsuranceCompanies,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription =   $"{ model.ModifiedByName } has updated { model.FullName} insurance company on {DateTime.UtcNow.AddMinutes(330)}" ,
                LocationId= Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);
            return this.Success("Insurance Company has been updated successfully.");
        }

        /// <summary>
        /// The delete Insurance Company.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Insurance Company deleted successfully.
        /// - 409 - Insurance Company 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]InsuranceCompanyModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (InsuranceCompanyModel)EmptyFilter.Handler(model);

                var insuranceCompanyName= await this.insuranceCompaniesServices.FindNameByInsuranceId(model.InsuranceCompanyId);

                var response = await this.insuranceCompaniesServices.DeleteAsync(model.InsuranceCompanyId);
                if (response == 0)
                {
                    return this.ServerError();
                }

                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.CreatedBy,
                    LogTypeId = (int)LogTypes.InsuranceCompanies,
                    LogFrom = (int)AccountType.Administrator,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    LogDescription = $"{ model.ModifiedByName } has deleted {insuranceCompanyName} insurance company on {DateTime.UtcNow.AddMinutes(330)}",
                    LocationId= Convert.ToInt32(header.LocationId)
                };
                await this.auditLogServices.LogAsync(auditLogModel);

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

                return this.ServerError();
            }
        }

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

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.ModifiedBy,
                LogTypeId = (int)LogTypes.InsuranceCompanies,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $"{ model.ModifiedByName } has updated {model.FullName} insurance company status to {(model.Active ? "'Active'" : "'Inactive'")} on {DateTime.UtcNow.AddMinutes(330)}",
                LocationId= Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

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