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

namespace Indotalent.Features.Inventory.PositiveAdjustment.Cqrs;

public class UpdatePositiveAdjustmentRequest
{
    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 UpdatePositiveAdjustmentCommand(UpdatePositiveAdjustmentRequest Data) : IRequest<bool>;

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

    public async Task<bool> Handle(UpdatePositiveAdjustmentCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.PositiveAdjustment
            .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.PositiveAdjustment))
            .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;
    }
}