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

namespace EnotaryoPH.Web.Pages.Notary.Dashboard
{
    public class DashboardModel : PageModel
    {
        private readonly NotaryoDBContext _dbContext;
        private readonly ICurrentUserService _currentUserService;

        public DashboardModel(NotaryoDBContext dbContext, ICurrentUserService currentUserService)
        {
            _dbContext = dbContext;
            _currentUserService = currentUserService;
        }

        public IActionResult OnGet()
        {
            var currentUser = _dbContext.Users
                .Single(u => u.User_UID == _currentUserService.GetUser_UID());

            AvailableItems = _dbContext.Transactions
                .Include(t => t.TransactionDocument)
                .Include(t => t.Lawyer)
                .Include(t => t.PreferredLawyer)
                .Where(t => t.Status == nameof(TransactionState.Submitted) && t.Lawyer.UserID != currentUser.UserID && t.PreferredLawyer.UserID != currentUser.UserID)
                .Select(t => new DashboardItem
                {
                    Date = t.CreatedOn.Value,
                    Link = $"/Notary/TransactionStatus/{t.Transaction_UID}",
                    Status = t.Status,
                    Type = t.TransactionDocument.DocumentType
                })
                .OrderByDescending(t => t.Date)
                .ToList();

            MyItems = _dbContext.Transactions
                .Include(t => t.TransactionDocument)
                .Include(t => t.Lawyer)
                .Include(t => t.PreferredLawyer)
                .Where(t => (t.Status == nameof(TransactionState.Submitted) && t.PreferredLawyer.UserID == currentUser.UserID) || (t.Status == nameof(TransactionState.Accepted) && t.Lawyer.UserID == currentUser.UserID))
                .Select(t => new DashboardItem
                {
                    Date = t.CreatedOn.Value,
                    Link = t.Status == nameof(TransactionState.Accepted) ? $"/Participant/VideoCall/Room/{t.Transaction_UID}" : $"/Notary/TransactionStatus/{t.Transaction_UID}",
                    Status = t.Status,
                    Type = t.TransactionDocument.DocumentType
                })
                .OrderByDescending(t => t.Date)
                .ToList();

            return Page();
        }

        public List<DashboardItem> AvailableItems { get; set; }
        public List<DashboardItem> MyItems { get; set; }
    }
}