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 ROUTES NO AUTH
    [Produces("text/plain")]
    [Route("rvr")]
    public class RvrController : Controller //RAVEN trial license request 
    {
        private readonly rockfishContext ct;


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

        public class dtoRequest
        {
            [Required]
            public Guid DbId { get; set; }
            [Required, EmailAddress]
            public string Email { get; set; }
            [Required]
            public string Company { get; set; }
            [Required]
            public string Contact { get; set; }
        }

#if (DEBUG)
        private const string LICENSE_SERVER_URL = "http://localhost:3001/";
        public const string SUPPORT_EMAIL = "cardjohn@ayanova.com";
#else
        private const string LICENSE_SERVER_URL = "https://rockfish.ayanova.com/";
        public const string SUPPORT_EMAIL="support@ayanova.com";
#endif

        //### CUSTOMER ROUTE CALLED FROM RAVEN ####
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] dtoRequest r)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (r.DbId == Guid.Empty)
            {
                return BadRequest("E1000 - DBId invalid");
            }

            //can't do this if there is a purchased license with this dbid already
            if (await ct.License.Where(z => z.DbId == r.DbId).AnyAsync())
            {
                return BadRequest("E1000 - Can't trial; there is already a purchased license issued for this database Id");
            }

            //can't do this if there is a trial request already pending
            if (await ct.TrialRequest.Where(z => z.DbId == r.DbId && z.DtProcessed == null).AnyAsync())
            {
                return Ok("Request awaiting approval");
            }


            System.Diagnostics.Debug.WriteLine("RvRController:Post - TODO: Test MustBeOlderThan date code");

            //if there is an active trial for this db then can't do this they must request we re-release it or completely zap the database instead
            var MustBeOlderThan = DateUtil.DateToEpoch(DateTime.Now.AddDays((RavenKeyFactory.TRIAL_PERIOD_DAYS * -1)));
            if (await ct.TrialRequest.Where(z => z.DbId == r.DbId && z.DtProcessed != null && z.DtProcessed > MustBeOlderThan).AnyAsync())
            {
                return BadRequest("E1000 - Can't trial; there is already an active trial license issued for this database Id");
            }

            //Everything seems to be in order, save the request and return ok
            var NewRequest = new TrialRequest();
            NewRequest.Email = r.Email;
            NewRequest.DbId = r.DbId;
            NewRequest.CompanyName = r.Company;
            NewRequest.ContactName = r.Contact;
            await ct.TrialRequest.AddAsync(NewRequest);
            await ct.SaveChangesAsync();
            NewRequest.EmailConfirmCode = NewRequest.Id.ToString() + FetchKeyCode.generate();
            await ct.SaveChangesAsync();
            var verifyUrl = LICENSE_SERVER_URL + $"rvr/verify/{NewRequest.EmailConfirmCode}";
            var body = $"Please verify your email address by clicking the link below or copy and pasting into a browser\r\n{verifyUrl}\r\n(If you did not request this you can ignore this message)";
            //send confirmation email
            RfMail.SendMessage("support@ayanova.com", NewRequest.Email, "AyaNova trial request email verification", body, false);
            //return Ok(new { Accepted = true });
            return Accepted();

        }

        //### CUSTOMER ROUTE CALLED FROM CUSTOMER BROWSER / EMAIL ####
        [HttpGet("verify/{code}")]
        public async Task<IActionResult> GetVerify([FromRoute] string code)
        {
            //is there a valid trial request
            var req = await ct.TrialRequest.Where(z => z.EmailConfirmCode == code && z.DtFetched == null && z.Status == TrialRequest.TrialRequestStatus.NotSet).FirstOrDefaultAsync();
            if (req == null)
            {
                return new ContentResult
                {
                    ContentType = "text/html",
                    StatusCode = 200,
                    Content = "<html><body><h4>Request not found</h4><p>There was no evaluation request associated with this verification code.</p></body></html>"
                };
            }

            req.EmailValidated = true;
            await ct.SaveChangesAsync();

            //notify *us*
            //http://localhost:3001/default.htm#!/trials/[id]
            var rfUrl = LICENSE_SERVER_URL + $"default.htm#!/trialEdit/{req.Id}";
            var body = $"Email address {req.Email} was just verified for {req.ContactName} at {req.CompanyName}.\r\nTrial key is ready to be processed now:\r\n{rfUrl}";
            //send confirmation email
            RfMail.SendMessage("support@ayanova.com", SUPPORT_EMAIL, "AyaNova trial request requiring action", body, false);

            return new ContentResult
            {
                ContentType = "text/html",
                StatusCode = 200,
                Content = "<html><body><h4>Email validated!</h4><p>Your request is being processed and you will receive an email with instructions for starting your AyaNova evaluation.</p></body></html>"
            };
        }

    }//eoc
}//eons