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

namespace Application.Features.Admin.Member.Wallet.List.Charge;

public sealed class Handler(IAppDbContext db) : ICommandHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        var wallet = await db.Wallet.Include(x => x.Balances).Include(x => x.Transactions).FirstOrDefaultAsync(x => x.ID == request.WalletID, ct);

        if (wallet is null)
        {
            throw new KeyNotFoundException("지갑을 찾을 수 없습니다.");
        }

        var amount = Money.KRW(Math.Abs(request.Amount));
        var reason = request.Amount > 0 ? "관리자 충전" : "관리자 차감";

        if (request.Amount > 0)
        {
            wallet.AdjustIncrease(amount, reason, memo: request.Memo);
        }
        else if (request.Amount < 0)
        {
            wallet.AdjustDecrease(amount, reason, memo: request.Memo);
        }
        else
        {
            throw new ArgumentException("충전 금액을 입력해주세요.");
        }

        await db.SaveChangesAsync(ct);
    }
}