using GmRelay.Shared.Domain;

namespace GmRelay.Shared.Rendering;

public static class SessionBatchViewBuilder
{
    public static SessionBatchViewModel Build(
        string title,
        IReadOnlyList<SessionBatchDto> sessions,
        IReadOnlyList<ParticipantBatchDto> participants)
    {
        var orderedSessions = sessions.OrderBy(s => s.ScheduledAt).ToList();
        var sessionItems = new List<SessionViewItem>();

        foreach (var session in orderedSessions)
        {
            var activePlayers = participants
                .Where(p => p.SessionId == session.SessionId && p.RegistrationStatus == ParticipantRegistrationStatus.Active)
                .Select(p => new PlayerViewItem(p.DisplayName, p.TelegramUsername, p.RegistrationStatus))
                .ToList();

            var waitlistedPlayers = participants
                .Where(p => p.SessionId == session.SessionId && p.RegistrationStatus == ParticipantRegistrationStatus.Waitlisted)
                .Select(p => new PlayerViewItem(p.DisplayName, p.TelegramUsername, p.RegistrationStatus))
                .ToList();

            var actions = new List<AvailableAction>();
            if (!SessionStatus.IsCancelled(session.Status))
            {
                var dateTitle = session.ScheduledAt.FormatMoscowShort();
                var joinLabel = GetJoinButtonText(session, activePlayers.Count, dateTitle);
                actions.Add(new AvailableAction("join_session", joinLabel, session.SessionId));
                actions.Add(new AvailableAction("leave_session", $"🚪 Выйти {dateTitle}", session.SessionId));
            }

            sessionItems.Add(new SessionViewItem(
                session.SessionId,
                session.ScheduledAt,
                session.Status,
                session.MaxPlayers,
                session.JoinLink,
                activePlayers.Count,
                activePlayers,
                waitlistedPlayers,
                actions));
        }

        return new SessionBatchViewModel(title, sessionItems);
    }

    private static string GetJoinButtonText(SessionBatchDto session, int activePlayers, string dateTitle)
    {
        if (session.MaxPlayers.HasValue && activePlayers >= session.MaxPlayers.Value)
        {
            return $"⏳ В лист ожидания {dateTitle}";
        }

        return $"✋ На {dateTitle}";
    }
}
// trigger pr
