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

namespace Indotalent.Features.Inventory.TransferIn.Cqrs;

public class UpdateTransferInRequest
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? TransferReceiveDate { get; set; }
    public Data.Enums.TransferStatus Status { get; set; }
    public string? Description { get; set; }
    public string? TransferOutId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdateTransferInCommand(UpdateTransferInRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.TransferReceiveDate = request.Data.TransferReceiveDate;
        entity.Status = request.Data.Status;
        entity.Description = request.Data.Description;
        entity.TransferOutId = request.Data.TransferOutId;

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

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

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