using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Sockeye.Models;
using Sockeye.Api.ControllerHelpers;
using Newtonsoft.Json.Linq;
using System;
using Sockeye.Biz;

namespace Sockeye.Api.Controllers
{

    [Produces("application/json")]
    [Route("api/order")]
    public class OrderController : ControllerBase
    {

        private readonly AyContext ct;
        private readonly ILogger<OrderController> log;
        private readonly ApiServerState serverState;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="dbcontext"></param>
        /// <param name="logger"></param>
        /// <param name="apiServerState"></param>  
        public OrderController(AyContext dbcontext, ILogger<OrderController> logger, ApiServerState apiServerState)
        {
            ct = dbcontext;
            log = logger;
            serverState = apiServerState;
        }
        //Receive an order notification from ShareIt
        //https://account.mycommerce.com/home/wiki/7479805
        [HttpPost("shareit")]
        public async Task<IActionResult> Post([FromHeader] string Authorization, [FromBody] JObject j)
        {
            if (!serverState.IsOpen)
            {
                var msg = ("Server state was not open when Vendor Order notification received; returning 503 (temp. unavailable) to them, they should retry when server open again.");
                log.LogError(msg);
                await NotifyEventHelper.AddOpsProblemEvent(msg);
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            }

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {                
                (string username, string password) = Sockeye.Util.AutoOrderProcessingUtil.GetUsernameAndPasswordFromAuthorizeHeader(Authorization);                
                if (username == "Y24PYYDQSA1L12905N5MKU" && password == "MA8GMQK2PC3FDNT1RTR68R")
                {                    
                    //save it to the database
                    var vn = new VendorNotification();
                    vn.Created = DateTime.UtcNow;
                    vn.VendorId = 1;//MyCommerce/shareit is vendor 1, for now that's all that's needed
                    vn.VendorData = j.ToString();
                    await ct.VendorNotification.AddAsync(vn);
                    await ct.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex, "OrderController/shareit - Exception processing vendor notification, returned 503 to vendor");
                await NotifyEventHelper.AddOpsProblemEvent("OrderController/shareit - Exception processing vendor notification, see log");
                 return StatusCode(503);//ask it to retry again later
            }
            return Ok("ok");//shareit notifier looks for an OK response to know if it should resend or not https://account.mycommerce.com/home/wiki/7479805
        }
        //------------


    }//eoc
}//eons