using Hims.Api.Models;
using Hims.Api.Utilities;
using Hims.Domain.Services;
using Hims.Shared.DataFilters;
using Hims.Shared.EntityModels;
using Hims.Shared.Library.Enums;
using Hims.Shared.UserModels.Common;
using Hims.Shared.UserModels;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Authorization;
using Npgsql;

namespace Hims.Api.Controllers
{
    /// <inheritdoc />
    [Authorize]
    [Route("api/authorityMaster")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class AuthorityMasterController : BaseController
    {

        /// <summary>
        /// The authority services.
        /// </summary>
        private readonly IAuthorityMasterService authorityMasterService;

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

        /// <inheritdoc />
        public AuthorityMasterController(IAuthorityMasterService authorityMasterService, IAuditLogService auditLogService)
        {
            this.authorityMasterService = authorityMasterService;
            this.auditLogServices = auditLogService;
        }

        /// <summary>
        /// Inserts the hoc asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="header">The location.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("add")]
        public async Task<ActionResult> InsertAsync([FromBody] AuthorityMasterModel model, [FromHeader] LocationHeader header)
        {
            model = (AuthorityMasterModel)EmptyFilter.Handler(model);
            var response = await this.authorityMasterService.InsertAsync(model);
            try
            {
                if (response > 0)
                {
                    var auditLog = new AuditLogModel
                    {
                        AccountId = model.CreatedBy,
                        LogTypeId = (int)LogTypes.AuthorityMaster,
                        LogDate = DateTime.Now,
                        LogFrom = (short)model.LoginRoleId,
                        LogDescription = $"<b>{model.CreatedByName}</b> has <b>added</b> Authority of <b>{model.Authority}</b> successfully.",
                        LocationId = Convert.ToInt32(header.LocationId)
                    };
                    await this.auditLogServices.LogAsync(auditLog);
                }
            }
            catch (Exception ex)
            {
                //ignore
            }
            return this.Success(response);
        }
        /// <summary>
        /// Update the hoc asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="header">The location.</param>
        /// <returns></returns>

        [HttpPost]
        [Route("update")]
        public async Task<ActionResult> UpdateAsync([FromBody] AuthorityMasterModel model, [FromHeader] LocationHeader header)
        {
            model = (AuthorityMasterModel)EmptyFilter.Handler(model);
            var response = await this.authorityMasterService.UpdateAsync(model);
            if (response > 0)
            {
                    var auditLog = new AuditLogModel
                    {
                        AccountId = model.CreatedBy,
                        LogTypeId = (int)LogTypes.AuthorityMaster,
                        LogDate = DateTime.Now,
                        LogFrom = short.Parse(model.LoginRoleId.ToString()),
                        LogDescription = $"<b>{model.CreatedByName}<b> has <b>updated<b> Authority of <b>{model.Authority}</b> successfully.",
                        LocationId = Convert.ToInt32(header.LocationId)
                    };
                    await this.auditLogServices.LogAsync(auditLog);
            }
           
            return this.Success(response);
        }

        /// <summary>
        /// Fetches all asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("fetch-all")]
        public async Task<ActionResult> FetchAsync([FromBody] AuthorityMasterModel model)
        {
            model = (AuthorityMasterModel)EmptyFilter.Handler(model);
            var response = await this.authorityMasterService.FetchAllAsync(model);
            return this.Success(response);
        }



        [HttpPost]
        [Route("modify-status")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyStatusAsync([FromBody] AuthorityMasterModel model, [FromHeader] LocationHeader header)
        {
            model = (AuthorityMasterModel)EmptyFilter.Handler(model);
            var response = await this.authorityMasterService.ActivateOrDeactivateTest(model);
            if (response == 0)
            {
                return this.ServerError();
            }

            var auditLogModel = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.AuthorityMaster,
                LogFrom = (int)AccountType.Administrator,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $@"<b>{model.CreatedByName}</b> has <b>{((bool)model.Active ? "Activated" : "Deactivated")}</b> the Authority <b>{model.Authority}</b> successfully",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);

            return this.Success(response);

        }
        /// <summary>
        /// The delete specialization.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <param name="header">
        /// The location header.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("delete")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> DeleteAsync([FromBody] AuthorityMasterModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (AuthorityMasterModel)EmptyFilter.Handler(model);
                var response = await this.authorityMasterService.DeleteAsync(model);
                if (response == 0)
                {
                    return this.ServerError();
                }
                if (response > 0)
                {
                    var auditLog = new AuditLogModel
                    {
                        AccountId = model.CreatedBy,
                        LogTypeId = (int)LogTypes.AuthorityMaster,
                        LogDate = DateTime.Now,
                        LogFrom = (int)AccountType.Administrator,
                        LogDescription = $"<b>{model.CreatedByName}</b> had <b>deleted</b> the <b>{model.Authority}</b> on {DateTime.UtcNow.AddMinutes(330)}",
                        LocationId = Convert.ToInt32(header.LocationId)
                    };
                    await this.auditLogServices.LogAsync(auditLog);
                }

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

    }
}
