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

namespace Application.Features.Api.Crew.AddMember;

internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Response>
{
    public async Task<Response> Handle(Command request, CancellationToken ct)
    {
        var crew = await db.Crew
            .FirstOrDefaultAsync(c => c.ID == request.CrewID, ct);

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

        // 이미 등록된 크루원인지 확인
        var exists = await db.CrewMember
            .AnyAsync(m => m.CrewID == request.CrewID && m.MemberID == request.TargetMemberID, ct);

        if (exists)
        {
            throw new InvalidOperationException("이미 등록된 크루원입니다.");
        }

        // 대상 회원의 채널 ID 조회
        var channel = await db.Channel.AsNoTracking()
            .FirstOrDefaultAsync(c => c.MemberID == request.TargetMemberID, ct);

        var member = CrewMember.Create(
            request.CrewID,
            request.TargetMemberID,
            request.Nickname,
            channel?.ID,
            request.Role,
            request.SortOrder
        );

        db.CrewMember.Add(member);
        await db.SaveChangesAsync(ct);

        return new Response(member.ID);
    }
}