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 readonly IVideoConferenceService _videoConferenceService;
        private Transaction _transactionEntity;

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

        public async Task<IActionResult> OnGetAsync()
        {
            _transactionEntity = _dbContext.Transactions
               .Include(t => t.TransactionSignatories)
               .ThenInclude(ts => ts.User)
               .Include(t => t.Lawyer)
               .ThenInclude(l => l.User)
               .Include(t => t.Principal)
               .FirstOrDefault(t => t.Transaction_UID == Transaction_UID);
            if (_transactionEntity == null || _transactionEntity.Status.IsInList(TransactionState.Completed))
            {
                return NotFound();
            }

            if (_videoConferenceService.CanStart(Transaction_UID))
            {
                return Redirect($"/Participant/VideoCall/Room/{Transaction_UID}");
            }

            var participants = _transactionEntity.TransactionSignatories
                .ConvertAll(t => new WaitingForParticipantViewModel
                {
                    Email = t.Email,
                    Status = ConvertToWaitingStatus(t.Status),
                    Type = string.Equals(t.Email, _currentUserService.GetEmail(), StringComparison.OrdinalIgnoreCase) ? "(You)" : t.Type,
                    UID = t.TransactionSignatory_UID.GetValueOrDefault(),
                    SortOrder = 3
                });

            participants.Add(new WaitingForParticipantViewModel
            {
                Email = _transactionEntity.Lawyer?.User?.Email ?? "notarypublic@enotaryo.ph",
                Status = "Waiting",
                Type = nameof(UserType.Notary),
                UID = _transactionEntity.Lawyer?.User?.User_UID ?? Guid.Empty,
                SortOrder = 1
            });

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

            Participants = participants.OrderBy(p => p.SortOrder).ThenBy(p => p.Email).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; }
    }
}