using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using rockfishCore.Models;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using rockfishCore.Util;

namespace rockfishCore.Controllers
{
    //Authentication controller
    [Produces("application/json")]
    [Route("api/trial")]
    [Authorize]
    public class TrialController : Controller
    {
        private readonly rockfishContext ct;
        private readonly IConfiguration _configuration;
        public TrialController(rockfishContext context, IConfiguration configuration)//these two are injected, see startup.cs
        {
            ct = context;
            _configuration = configuration;
        }


        //Fetch list of trial requests
        [HttpGet("list")]
        public async Task<IActionResult> GetRequestsAsync()
        {
            var ret = await ct.TrialRequest.AsNoTracking().OrderByDescending(z => z.DtRequested).ToListAsync();
            return Ok(ret);
        }


        //case 3233 GET: api/Trial/5
        [HttpGet("{id}")]
        public async Task<IActionResult> GetTrial([FromRoute] long id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var ret = await ct.TrialRequest.AsNoTracking().SingleOrDefaultAsync(m => m.Id == id);
            if (ret == null)
            {
                return NotFound();
            }

            return Ok(ret);
        }

        // DELETE: api/Trial/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteTrial([FromRoute] long id)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            var rec = await ct.TrialRequest.SingleOrDefaultAsync(m => m.Id == id);
            if (rec == null)
                return NotFound();
            ct.TrialRequest.Remove(rec);
            await ct.SaveChangesAsync();
            return Ok(rec);
        }

        //Approve
        [HttpPost("approve/{id}")]
        public async Task<IActionResult> ApproveTrial([FromRoute] long id)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            var trial = await ct.TrialRequest.SingleOrDefaultAsync(m => m.Id == id);
            if (trial == null)
                return NotFound();
            //DO APPROVE
            //check not already processed and ignore if so
            if (trial.DtProcessed != null)
            {
                //already processed, nothing to do here
                return BadRequest("Already processed");
            }

            //generate license key and insert in record
            trial.Key = RavenKeyFactory.GetRavenTrialKey(trial.DbId, trial.CompanyName);
            trial.Status = TrialRequest.TrialRequestStatus.Approved;
            trial.DtProcessed = DateUtil.NowAsEpoch();
            await ct.SaveChangesAsync();

            //send approved email to user
            var body = $"Your trial license request has been approved.\r\nThe license will fetch and install automatically shortly or you can fetch it now in the License form menu.";
            //send confirmation email
            RfMail.SendMessage("support@ayanova.com", trial.Email, "AyaNova trial request approved", body, false);

            return Ok(trial);

        }


        //Reject
        [HttpPost("reject/{id}")]
        public async Task<IActionResult> RejectTrial([FromRoute] long id, [FromQuery] string rejectReason)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            var trial = await ct.TrialRequest.SingleOrDefaultAsync(m => m.Id == id);
            if (trial == null)
                return NotFound();
            //DO REJECT
            //check not already processed and ignore if so
            if (trial.DtProcessed != null)
            {
                //already processed, nothing to do here
                return BadRequest("Already processed");
            }
            //generate license key and insert in record
            trial.RejectReason = rejectReason;
            trial.Status = TrialRequest.TrialRequestStatus.Rejected;
            trial.DtProcessed = DateUtil.NowAsEpoch();
            await ct.SaveChangesAsync();

            //send approved email to user
            string reason = string.Empty;
            if (!string.IsNullOrWhiteSpace(rejectReason))
            {
                reason = $"The request was rejected due to:\r\n{rejectReason}";
            }
            var body = $"Your trial license request was not approved.\r\n{reason}";
            //send confirmation email
            RfMail.SendMessage("support@ayanova.com", trial.Email, "AyaNova trial request not approved", body, false);

            return Ok(trial);

        }





        private async Task<bool> TrialRequestExistsAsync(long id)
        {
            return await ct.TrialRequest.AnyAsync(e => e.Id == id);
        }


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

    }//eoc
}//eons