using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Sales.SalesReturn.Cqrs;

public class UpdateSalesReturnItemRequest
{
    public string? Id { get; set; }
    public string? WarehouseId { get; set; }
    public string? ProductId { get; set; }
    public double? Movement { get; set; }
}

public record UpdateSalesReturnItemCommand(UpdateSalesReturnItemRequest Data) : IRequest<bool>;

public class UpdateSalesReturnItemHandler : IRequestHandler<UpdateSalesReturnItemCommand, bool>
{
    private readonly AppDbContext _context;
    public UpdateSalesReturnItemHandler(AppDbContext context) => _context = context;

    public async Task<bool> Handle(UpdateSalesReturnItemCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.InventoryTransaction
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (entity == null) return false;

        entity.WarehouseId = request.Data.WarehouseId;
        entity.ProductId = request.Data.ProductId;
        entity.Movement = request.Data.Movement;

        _context.CalculateInvenTrans(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return true;
    }
}