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

namespace Indotalent.Features.Sales.DeliveryOrder.Cqrs;

public class UpdateDeliveryOrderRequest
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? DeliveryDate { get; set; }
    public Data.Enums.DeliveryOrderStatus Status { get; set; }
    public string? Description { get; set; }
    public string? SalesOrderId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdateDeliveryOrderCommand(UpdateDeliveryOrderRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.DeliveryDate = request.Data.DeliveryDate;
        entity.Status = request.Data.Status;
        entity.Description = request.Data.Description;
        entity.SalesOrderId = request.Data.SalesOrderId;

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

        foreach (var trans in transactions)
        {
            trans.MovementDate = entity.DeliveryDate ?? DateTime.Now;
            trans.ModuleNumber = entity.AutoNumber;
            trans.Status = (Data.Enums.InventoryTransactionStatus)entity.Status;
            _context.CalculateInvenTrans(trans);
        }

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