using Application.Abstractions.Data; using Application.Abstractions.Messaging; using Domain.Entities.Donations; using Domain.Entities.Donations.ValueObject; using Microsoft.EntityFrameworkCore; using SharedKernel.Results; namespace Application.Features.Api.ChannelTitle.CreateChannelTitle; internal sealed class Handler(IAppDbContext db) : ICommandHandler> { public async Task> Handle(Command request, CancellationToken ct) { var channel = await db.Channel.FirstOrDefaultAsync(c => c.ID == request.ChannelID, ct); if (channel is null) { return Result.Failure(Error.NotFound("ChannelTitle.ChannelNotFound", "채널을 찾을 수 없습니다.")); } if (channel.MemberID != request.MemberID) { return Result.Failure(Error.Forbidden("ChannelTitle.Forbidden", "본인 채널만 수정할 수 있습니다.")); } var count = await db.ChannelTitle.CountAsync(t => t.ChannelID == request.ChannelID, ct); if (count >= DonationConstants.Title.MaxTitlesPerChannel) { return Result.Failure(Error.Problem("ChannelTitle.TooMany", $"칭호는 최대 {DonationConstants.Title.MaxTitlesPerChannel}개까지 등록할 수 있습니다.")); } if (string.IsNullOrWhiteSpace(request.Name)) { return Result.Failure(Error.Problem("ChannelTitle.NameRequired", "칭호 이름을 입력해 주세요.")); } if (request.Name.Length > 20) { return Result.Failure(Error.Problem("ChannelTitle.NameTooLong", "칭호 이름은 20자 이내여야 합니다.")); } if (request.MinAmount < 0) { return Result.Failure(Error.Problem("ChannelTitle.InvalidAmount", "최소 금액은 0원 이상이어야 합니다.")); } var duplicateAmount = await db.ChannelTitle.AnyAsync(t => t.ChannelID == request.ChannelID && t.MinAmount == request.MinAmount, ct); if (duplicateAmount) { return Result.Failure(Error.Conflict("ChannelTitle.DuplicateAmount", "같은 최소 금액의 칭호가 이미 존재합니다.")); } var entity = Domain.Entities.Donations.ChannelTitle.Create(request.ChannelID, request.Name, request.MinAmount, request.Color); entity.Update(request.Name, request.Description, request.MinAmount, request.Color, request.IconUrl, true); entity.SetOrder(count); await db.ChannelTitle.AddAsync(entity, ct); await db.SaveChangesAsync(ct); return Result.Success(entity.ID); } }