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

namespace Indotalent.Features.Inventory.NegativeAdjustment.Cqrs;

public class UpdateNegativeAdjustmentRequest
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? AdjustmentDate { get; set; }
    public Data.Enums.AdjustmentStatus Status { get; set; }
    public string? Description { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdateNegativeAdjustmentCommand(UpdateNegativeAdjustmentRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.AdjustmentDate = request.Data.AdjustmentDate;
        entity.Status = request.Data.Status;
        entity.Description = request.Data.Description;

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

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

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