using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using rockfishCore.Models;
using rockfishCore.Util;
using System.ComponentModel.DataAnnotations;

namespace rockfishCore.Controllers
{
    //### CUSTOMER ROUTE CALLED FROM RAVEN NO AUTH ####
    [Produces("application/json")]
    [Route("rvf")]
    public class RvfController : Controller //RAVEN License fetch route
    {
        private readonly rockfishContext ct;

        public RvfController(rockfishContext context)
        {
            ct = context;
        }

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

        //### CUSTOMER ROUTE CALLED FROM RAVEN ####
        [HttpPost]
        public async Task<IActionResult> PostLicenseFetchRequest([FromBody] dtoFetchRequest fetchRequest, [FromQuery] bool dtt, [FromQuery] bool pp)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            string FetchRequestDbId = fetchRequest.DbId;

            if (dtt)
            {
                return Ok(new
                {
                    data = new
                    {
                        key = RavenKeyFactory.GetRavenTestKey(FetchRequestDbId, pp)//pp means perpetual no pp means subcription
                    }
                });
            }

            string LicenseKey = null;
            //check for a key for this dbid, first check licensed then check trial




            //NO! this is a bug, it causes older keys that weren't fetched to be sent over most recent keys that were fetched :(
            //var PurchasedLicense = await ct.License.Where(z => z.DbId == FetchRequestDbId && z.Fetched == false).FirstOrDefaultAsync();

            //Get the most recent licensed key for this dbid regardless if fetched or not, most recent is most recent and supersedes any other keys
            var PurchasedLicense = await ct.License.OrderByDescending(z => z.Id).Where(z => z.DbId == FetchRequestDbId).FirstOrDefaultAsync();
            if (PurchasedLicense != null)
            {
                //Found a recent purchased key, if not fetched then can be sent
                if (!PurchasedLicense.Fetched)
                {
                    LicenseKey = PurchasedLicense.Key;
                    PurchasedLicense.Fetched = true;
                    PurchasedLicense.DtFetched = DateUtil.NowAsEpoch();
                    await ct.SaveChangesAsync();
                }
            }
            else
            {
                //is there an Approved UnFetched trial request for this DB ID? 
                //var req = await ct.TrialRequest.Where(z => z.DbId == FetchRequestDbId && z.DtFetched == null && z.Status == TrialRequest.TrialRequestStatus.Approved).FirstOrDefaultAsync();

                //only get most recent one if more than one
                var req = await ct.TrialRequest.OrderByDescending(z => z.Id).Where(z => z.DbId == FetchRequestDbId && z.Status == TrialRequest.TrialRequestStatus.Approved).FirstOrDefaultAsync();
                if (req == null || req.DtFetched != null)
                {
                    //none found or at least the most recent one found has already been fetched
                    return NotFound();
                }
                LicenseKey = req.Key;
                req.DtFetched = DateUtil.NowAsEpoch();
                await ct.SaveChangesAsync();
            }

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

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


    }
}