using System;
using Hims.Shared.UserModels.Common;
using Hims.Shared.UserModels.ChargeManagement;

namespace Hims.Api.Controllers
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;

    using Domain.Services;
    using Hims.Api.Models;
    using Hims.Shared.EntityModels;
    using Hims.Shared.Library.Enums;
    using Hims.Shared.UserModels.ChargeModule;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Utilities;

    /// <inheritdoc />
    [Authorize]
    [Route("api/charge-management")]
    public class ChargeManagementController : BaseController
    {
        /// <summary>
        /// The service
        /// </summary>
        private readonly IChargeManagementService service;

        /// <summary>
        /// The audit log services.
        /// </summary>
        private readonly IAuditLogService auditLogServices;
        /// <summary>
        /// The charge module service.
        /// </summary>
        private readonly IChargeModuleService chargeModuleService;

        /// <inheritdoc />
        public ChargeManagementController(IChargeManagementService service, IAuditLogService auditLogServices, IChargeModuleService chargeModuleService)
        {
            this.service = service;
            this.auditLogServices = auditLogServices;
            this.chargeModuleService = chargeModuleService;
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("masters")]
        public async Task<ActionResult> FetchMastersAsync()
        {
            try
            {
                var response = await this.service.FetchMastersAsync().ConfigureAwait(false);
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("fetch")]
        public async Task<ActionResult> FetchAsync([FromBody] FilterModel model)
        {
            try
            {
                var response = await this.service.FetchAsync(model).ConfigureAwait(false);
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("insert")]
        public async Task<ActionResult> InsertAsync([FromBody] InsertModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                var response = await this.service.InsertAsync(model).ConfigureAwait(false);
                if(response > 0)
                {
                    var auditLogModel = new AuditLogModel
                    {
                        AccountId = model.CreatedBy,
                        LogTypeId = (int)LogTypes.ChargeManagement,
                        LogFrom = (int)AccountType.Administrator,
                        LogDate = DateTime.UtcNow.AddMinutes(330),
                        LocationId = Convert.ToInt32(header.LocationId),
                        LogDescription = $" <b>{model.ModifiedByName}</b> has added new charge <b>{model.ChargeName}</b> on {DateTime.UtcNow.AddMinutes(330)}"
                    };
                    await this.auditLogServices.LogAsync(auditLogModel);
                }
                return Ok(new GenericResponse
                {
                    Status = response switch
                    {
                        -1 => GenericStatus.Error,
                        -2 => GenericStatus.Info,
                        _ => GenericStatus.Success
                    },
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("update")]
        public async Task<ActionResult> UpdateAsync([FromBody] UpdateModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                var response = await this.service.UpdateAsync(model).ConfigureAwait(false);

                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.CreatedBy,
                    LogTypeId = (int)LogTypes.ChargeManagement,
                    LogFrom = (int)AccountType.Administrator,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    LocationId = Convert.ToInt32(header.LocationId),
                    LogDescription = $" <b>{model.ModifiedByName}</b> has updated the charge <b>{model.ChargeName}</b> on {DateTime.UtcNow.AddMinutes(330)}"
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                return Ok(new GenericResponse
                {
                    Status = response switch
                    {
                        -1 => GenericStatus.Error,
                        -2 => GenericStatus.Info,
                        _ => GenericStatus.Success
                    },
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// Fetches the services with charge asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="location">The location.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("fetch-with-charges")]
        public async Task<ActionResult> FetchServicesWithChargeAsync([FromBody] FilterModel model, [FromHeader] LocationHeader location)
        {
            //model ??= new LabMainDetailModel();
            //model.LocationId = Convert.ToInt32(location.LocationId);
            //var response = await this.labsService.FetchAllLabMainDetailAsync(model);
            var response = await this.service.FetchAsync(model).ConfigureAwait(false);
            var getModulesData = await this.chargeModuleService.GetRequiredDetailForChargeFetchAsync("services", Convert.ToInt32(location.LocationId));
            if (model.ChargeCategoryId != null && model.ChargeCategoryId > 0)
            {
                getModulesData.ChargeCategoryId = model.ChargeCategoryId;
            }
            if (getModulesData == null)
            {
                return this.Success(new List<ViewModel>());
            }

            foreach (var lab in response)
            {
                lab.Charges = new List<ChargeModuleDetailsModel>();
                getModulesData.ReferenceId = lab.ChargeId;
                lab.Charges = (await this.chargeModuleService.FetchGivenChargesAsync(getModulesData)).ToList();
            }

            return this.Success(response);
        }
    }
}