using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.Crew.SaveCrew;

internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command>
{
    public async Task Handle(Command r, CancellationToken ct)
    {
        if (r.ID.HasValue)
        {
            var crew = await db.Crew
                .FirstOrDefaultAsync(c => c.ID == r.ID.Value && c.ChannelID == r.ChannelID, ct);

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

            crew.Update(r.Name, r.Description, r.MinAmount, r.IsActive);
        }
        else
        {
            var crew = Domain.Entities.Donations.Crew.Create(r.ChannelID, r.MemberID, r.Name, r.Description, r.MinAmount);
            db.Crew.Add(crew);
        }

        await db.SaveChangesAsync(ct);
    }
}