using EnotaryoPH.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace EnotaryoPH.Web.Pages.Principal.TransactionStatus
{
    public class IndexModel : PageModel
    {
        private readonly NotaryoDBContext _notaryoDBContext;
        private readonly ICurrentUserService _currentUserService;

        public IndexModel(NotaryoDBContext notaryoDBContext, ICurrentUserService currentUserService)
        {
            _notaryoDBContext = notaryoDBContext;
            _currentUserService = currentUserService;
        }

        public IActionResult OnGet()
        {
            var user = _notaryoDBContext.Users.First(e => e.User_UID == _currentUserService.GetUser_UID());
            var transaction = _notaryoDBContext
                .Transactions
                .AsNoTracking()
                .Include(e => e.TransactionSignatories)
                .Include(e => e.TransactionDocument)
                .FirstOrDefault(e => e.Transaction_UID == Transaction_UID && e.PrincipalID == user.UserID);

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

            Title = transaction.TransactionDocument.DocumentType;
            StartedOn = transaction.CreatedOn.GetValueOrDefault();

            Signatories = transaction.TransactionSignatories.ConvertAll(s => new SignatoryViewModel
            {
                Email = s.Email,
                Type = s.Type,
                Status = s.Status
            });

            StatusDescription = Signatories.Count > 1
                ? "Not all signatories have signed up to enotaryo and completed the onboarding process. This transaction cannot proceed until this has been resolved."
                : "Please wait while our Notary Public team reviews your document.";

            return Page();
        }

        [BindProperty(SupportsGet = true)]
        public Guid Transaction_UID { get; set; }

        public List<SignatoryViewModel> Signatories { get; set; } = [];

        public string Title { get; set; }
        public DateTime StartedOn { get; set; }
        public string StatusDescription { get; set; }
    }
}