using Application.Abstractions.Hub;
using Infrastructure.Hubs;
using Web.Api.Common;
using MediatR;
using Microsoft.AspNetCore.SignalR;

namespace Web.Api.Endpoints.Donation;

/// <summary>크루원 참여 동의 — 동의 후 전원 동의 시 세션 활성화</summary>
internal sealed class CrewSessionConsent : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost("api/crew/session/consent", async (
            Application.Features.Api.Crew.ConsentSession.Command body,
            ISender sender,
            IHubContext<AppHub, IAppHubClient> appHub,
            Application.Abstractions.Data.IAppDbContext db,
            CancellationToken ct
        ) => {
            var data = await sender.Send(body, ct);

            // 세션의 크루 채널SID 조회
            var session = await Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions
                .FirstOrDefaultAsync(
                    Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions
                        .AsNoTracking(db.CrewSession)
                        .Where(s => s.ID == body.CrewSessionID),
                    ct
                );

            if (session is not null)
            {
                var crew = await Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions
                    .FirstOrDefaultAsync(
                        Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions
                            .AsNoTracking(db.Crew)
                            .Where(c => c.ID == session.CrewID),
                        ct
                    );

                if (crew is not null)
                {
                    var channel = await Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions
                        .FirstOrDefaultAsync(
                            Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions
                                .AsNoTracking(db.Channel)
                                .Where(c => c.ID == crew.ChannelID),
                            ct
                        );

                    var channelSID = channel?.SID ?? "";

                    // 동의 현황 브로드캐스트 (크루장에게)
                    var consents = await Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions
                        .ToListAsync(
                            Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions
                                .AsNoTracking(db.CrewSessionConsent)
                                .Where(c => c.CrewSessionID == body.CrewSessionID)
                                .Join(db.CrewMember, c => c.CrewMemberID, m => m.ID, (c, m) => new {
                                    c.CrewMemberID, m.Nickname, c.IsConsented, c.ConsentedAt
                                }),
                            ct
                        );

                    await appHub.Clients.Group($"channel:{channelSID}").ReceiveCrewConsentUpdate(new
                    {
                        CrewSessionID = body.CrewSessionID,
                        Consents = consents,
                        AllConsented = data.AllConsented
                    });

                    // 전원 동의 시 세션 시작 브로드캐스트
                    if (data.AllConsented)
                    {
                        await appHub.Clients.Group($"channel:{channelSID}").ReceiveCrewStarted(new
                        {
                            CrewSessionID = body.CrewSessionID,
                            Title = session.Title,
                            CrewName = crew.Name
                        });
                    }
                }
            }

            return ApiResponse.Ok(data);
        })
        .WithTags("Crew")
        .RequireAuthorization();
    }
}