using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Threading.Tasks;

namespace GatewayAPI
{
    public class HttpResponseMessageResult : IActionResult
    {
        private readonly HttpResponseMessage responseMessage;

        public HttpResponseMessageResult(HttpResponseMessage responseMessage)
        {
            this.responseMessage = responseMessage ?? throw new ArgumentNullException(nameof(responseMessage));
        }

        public async Task ExecuteResultAsync(ActionContext context)
        {
            HttpContext httpContext = context.HttpContext;
            HttpResponse response = httpContext.Response;

            response.ContentType = "application/json; charset=utf-8";

            // Copy the status code
            response.StatusCode = (int)responseMessage.StatusCode;

            // Copy the cookies
            if (responseMessage.Headers.TryGetValues("Set-Cookie", out var cookieValues))
            {
                foreach (string cookie in cookieValues)
                    response.Headers.Append("Set-Cookie", cookie);
            }

            // Copy the response body directly to the response stream
            using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())
            {
                await responseStream.CopyToAsync(response.Body);
                await response.Body.FlushAsync();
            }
        }
    }
}