using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Domain.Entities.Donations.ValueObject;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.Crew.RemoveMember;

internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        var member = await db.CrewMember
            .FirstOrDefaultAsync(m => m.ID == request.CrewMemberID, ct);

        if (member is null)
        {
            throw new KeyNotFoundException("크루원을 찾을 수 없습니다.");
        }

        // 진행 중인 세션이 있으면 삭제 불가
        var hasActiveSession = await db.CrewSession
            .AnyAsync(s => s.CrewID == member.CrewID && s.Status != CrewSessionStatus.Ended, ct);

        if (hasActiveSession)
        {
            throw new InvalidOperationException("진행 중인 크루 방송이 있어 삭제할 수 없습니다.");
        }

        db.CrewMember.Remove(member);
        await db.SaveChangesAsync(ct);
    }
}