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

    /// <inheritdoc />
    [Authorize]
    [Route("api/unit-type")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class UnitTypeController : BaseController
    {
        /// <summary>
        /// The unit type services.
        /// </summary>
        private readonly IUnitTypeService unitTypeService;

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

        /// <inheritdoc />
        public UnitTypeController(IUnitTypeService unitTypeService, IAuditLogService auditLogServices)
        {
            this.unitTypeService = unitTypeService;
            this.auditLogServices = auditLogServices;
        }

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

            }
            catch (Exception ex)
            {

            }
            return default;
        }


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

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

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

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

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

            return this.Success("Unit 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 - Unit Type deleted successfully.
        /// - 409 - Unit 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] DeleteModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (DeleteModel)EmptyFilter.Handler(model);
                var name = await this.unitTypeService.FindNameByUnitTypeId(model.UnitTypeId);
                var response = await this.unitTypeService.DeleteAsync(model);
                if (response == 0)
                {
                    return this.ServerError();
                }

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

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

                return this.ServerError();
            }
        }

    }
}