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

namespace Indotalent.Features.Inventory.TransferOut.Cqrs;

public class UpdateTransferOutRequest
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? TransferReleaseDate { get; set; }
    public Data.Enums.TransferStatus Status { get; set; }
    public string? Description { get; set; }
    public string? WarehouseFromId { get; set; }
    public string? WarehouseToId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdateTransferOutCommand(UpdateTransferOutRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.TransferReleaseDate = request.Data.TransferReleaseDate;
        entity.Status = request.Data.Status;
        entity.Description = request.Data.Description;
        entity.WarehouseFromId = request.Data.WarehouseFromId;
        entity.WarehouseToId = request.Data.WarehouseToId;

        var details = await _context.InventoryTransaction
            .Where(x => x.ModuleId == entity.Id && x.ModuleName == nameof(Data.Entities.TransferOut))
            .ToListAsync(cancellationToken);

        foreach (var item in details)
        {
            item.MovementDate = entity.TransferReleaseDate ?? DateTime.Now;
            item.Status = (Data.Enums.InventoryTransactionStatus)entity.Status;
            item.WarehouseId = entity.WarehouseFromId;
            item.ModuleNumber = entity.AutoNumber;
            _context.CalculateInvenTrans(item);
        }

        await _context.SaveChangesAsync(cancellationToken);
        return true;
    }
}