namespace Hims.Admin.Middleware
{
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Antiforgery;
    using Microsoft.AspNetCore.Http;

    /// <summary>
    /// Anti-forgery key
    /// </summary>
    public class AntiForgeryTokenMiddleware
    {
        /// <summary>
        /// The <see cref="antiForgery"/>.
        /// </summary>
        private readonly IAntiforgery antiForgery;

        /// <summary>
        /// Initializes a new instance of the <see cref="AntiForgeryTokenMiddleware"/> class.
        /// </summary>
        /// <param name="next">
        /// The next.
        /// </param>
        /// <param name="antiForgery">
        /// The <paramref name="antiForgery"/>.
        /// </param>
        public AntiForgeryTokenMiddleware(RequestDelegate next, IAntiforgery antiForgery)
        {
            this.Next = next;
            this.antiForgery = antiForgery;
        }

        /// <summary>
        /// Gets the next.
        /// </summary>
        private RequestDelegate Next { get; }

        /// <summary>
        /// The invoke.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public Task Invoke(HttpContext context)
        {
            var tokens = this.antiForgery.GetAndStoreTokens(context);
            context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
            return this.Next(context);
        }
    }
}
