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

    using Utilities;
    using Domain.Helpers;
    using Domain.Services;

    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json;
    using Shared.UserModels.WebNotification;
    using Hims.Shared.UserModels;
    using Hims.Shared.EntityModels;
    using Hims.Api.Models;
    using Hims.Domain.Entities;

    /// <summary>
    /// The notification controller.
    /// </summary>
    [Route("api/web-notification")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class NotificationController : BaseController
    {
        /// <summary>
        /// The notification service.
        /// </summary>
        private readonly IWebNotificationService notificationService;

        /// <summary>
        /// The AES helper.
        /// </summary>
        private readonly IAESHelper aesHelper;

        /// <summary>
        /// The document helper.
        /// </summary>
        private readonly IDocumentHelper documentHelper;

        /// <inheritdoc />
        public NotificationController(IWebNotificationService notificationService, IAESHelper aesHelper, IDocumentHelper documentHelper)
        {
            this.notificationService = notificationService;
            this.aesHelper = aesHelper;
            this.documentHelper = documentHelper;
        }

        /// <summary>
        /// Fetches the notifications asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="locationHeader"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("fetch")]
        public async Task<ActionResult> FetchNotificationsAsync([FromBody] WebNotificationFilterModel model, [FromHeader] LocationHeader locationHeader)
        {
            model ??= new WebNotificationFilterModel();
            model.LocationId = locationHeader != null && !string.IsNullOrEmpty(locationHeader.LocationId) ? int.Parse(locationHeader.LocationId) : (int?)null;
            var response = await this.notificationService.FetchNotificatons(model);
            foreach (var item in response)
            {
                if (item.ReferenceId != null)
                {
                    item.EncryptedReferenceId = this.aesHelper.Encode(item.ReferenceId.ToString());
                }
            }

            return this.Success(response);
        }
    }
}