using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using Sockeye.Models;
using Sockeye.Api.ControllerHelpers;
using System.ComponentModel.DataAnnotations;

namespace Sockeye.Api.Controllers
{
    [Route("rvf")]//v8 fetch license route
    [Produces("application/json")]
    public class RvfController : ControllerBase
    {

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

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="dbcontext"></param>
        /// <param name="logger"></param>
        /// <param name="apiServerState"></param>  
        public RvfController(AyContext dbcontext, ILogger<RvfController> logger, ApiServerState apiServerState)
        {
            ct = dbcontext;
            log = logger;
            serverState = apiServerState;
        }


        public class dtoFetchRequest
        {
            [Required]
            public string DbId { get; set; }
        }

        //### RAVEN FETCH LICENSE REQUEST HERE ####
        //This route is used by Raven to check if there is an unfetched license key and return it
        [HttpPost]
        public async Task<IActionResult> PostLicenseFetchRequest([FromBody] dtoFetchRequest fetchRequest)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            string FetchRequestDbId = fetchRequest.DbId;
            string LicenseKey = null;
            //Get the most recent  key for this dbid regardless if fetched or not, most recent is most recent and supersedes any other keys
            //for the same database id
            //this means if a user requests a trial key then buys a key but both are unfetched the bought key takes precedence or vice versa
            var license = await ct.License.OrderByDescending(z => z.Id).Where(z => z.DbId == FetchRequestDbId).FirstOrDefaultAsync();
            if (license != null)
            {
                //Found a recent purchased key, if not fetched then can be sent
                if (license.FetchedOn == null)
                {
                    LicenseKey = license.Key;
                    license.FetchedOn = System.DateTime.UtcNow;
                    await ct.SaveChangesAsync();
                }
            }

            if (LicenseKey == null)
            {
                return NotFound();
            }

            return Ok(new
            {
                data = new
                {
                    key = LicenseKey
                }
            });
        }

        //------------


    }//eoc
}//eons