using Application.Abstractions.Hub;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;

namespace Infrastructure.Hubs;

/// <summary>
/// 후원 전용 Hub — OBS 위젯, 리모콘 전용
/// 채널 SID 기반 그룹으로 분리
/// </summary>
public sealed class DonationHub(
    ILogger<DonationHub> logger
) : Hub<IDonationHubClient>
{
    public override async Task OnConnectedAsync()
    {
        logger.LogInformation("[DonationHub] Connected: {ConnectionId}", Context.ConnectionId);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        logger.LogInformation("[DonationHub] Disconnected: {ConnectionId}", Context.ConnectionId);
        await base.OnDisconnectedAsync(exception);
    }

    /// <summary>채널 그룹 참가 (OBS 위젯, 리모콘에서 호출)</summary>
    public async Task JoinChannel(string widgetToken)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, widgetToken);
        logger.LogInformation("[DonationHub] {ConnectionId} joined group {WidgetToken}", Context.ConnectionId, widgetToken);
    }

    /// <summary>채널 그룹 퇴장</summary>
    public async Task LeaveChannel(string widgetToken)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, widgetToken);
    }

    /// <summary>OBS 위젯에서 알림 전달 완료 보고</summary>
    public async Task AlertDelivered(int alertID)
    {
        // Handler에서 처리 — 여기서는 이벤트만 전달
        logger.LogInformation("[DonationHub] AlertDelivered: {AlertID}", alertID);
    }

    /// <summary>OBS 위젯에서 알림 전달 실패 보고</summary>
    public async Task AlertFailed(int alertID, string reason)
    {
        logger.LogWarning("[DonationHub] AlertFailed: {AlertID} — {Reason}", alertID, reason);
    }
}