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

namespace EnotaryoPH.Web.Pages.Participant.VideoCall
{
    public class WaitingModel : PageModel
    {
        private readonly NotaryoDBContext _dbContext;
        private readonly ICurrentUserService _currentUserService;
        private Transaction _transactionEntity;

        public WaitingModel(NotaryoDBContext notaryoDBContext, ICurrentUserService currentUserService)
        {
            _dbContext = notaryoDBContext;
            _currentUserService = currentUserService;
        }

        public IActionResult OnGet()
        {
            _transactionEntity = _dbContext.Transactions
                .Include(t => t.TransactionSignatories)
                .ThenInclude(ts => ts.User)
                .Include(t => t.Lawyer)
                .Include(t => t.Principal)
                .FirstOrDefault(t => t.Transaction_UID == Transaction_UID);
            if (_transactionEntity == null)
            {
                return NotFound();
            }

            var participants = _transactionEntity.TransactionSignatories
                .Select(t => new WaitingForParticipantViewModel
                {
                    Email = t.Email,
                    Status = ConvertToWaitingStatus(t.Status),
                    Type = t.Email == _currentUserService.GetEmail() ? "(You)" : t.Type,
                    UID = t.TransactionSignatory_UID.GetValueOrDefault()
                })
                .ToList();

            if (_transactionEntity.LawyerID > 0)
            {
                participants.Add(new WaitingForParticipantViewModel
                {
                    Email = _transactionEntity.Lawyer.User.Email,
                    Status = "Waiting",
                    Type = nameof(UserType.Notary),
                    UID = Guid.Empty
                });
            }

            participants.Add(new WaitingForParticipantViewModel
            {
                Email = _transactionEntity.Principal.Email,
                Status = "Ready",
                Type = nameof(UserType.Principal),
                UID = Guid.Empty
            });

            Participants = participants.OrderBy(p => p.Type).ToList();

            return Page();
        }

        private string ConvertToWaitingStatus(string status) => status switch { nameof(SignatoryStatus.FaceMatch) => "Ready", _ => "Waiting" };

        public List<WaitingForParticipantViewModel> Participants { get; set; }

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