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

namespace Indotalent.Features.Inventory.Scrapping.Cqrs;

public class UpdateScrappingRequest
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? ScrappingDate { get; set; }
    public Data.Enums.ScrappingStatus Status { get; set; }
    public string? Description { get; set; }
    public string? WarehouseId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdateScrappingCommand(UpdateScrappingRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.ScrappingDate = request.Data.ScrappingDate;
        entity.Status = request.Data.Status;
        entity.Description = request.Data.Description;
        entity.WarehouseId = request.Data.WarehouseId;

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

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

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