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

namespace Indotalent.Features.Purchase.GoodsReceive.Cqrs;

public class UpdateGoodsReceiveRequest
{
    public string? Id { get; set; }
    public DateTime? ReceiveDate { get; set; }
    public Data.Enums.GoodsReceiveStatus Status { get; set; }
    public string? AutoNumber { get; set; }
    public string? Description { get; set; }
    public string? PurchaseOrderId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdateGoodsReceiveCommand(UpdateGoodsReceiveRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.ReceiveDate = request.Data.ReceiveDate;
        entity.Status = request.Data.Status;
        entity.Description = request.Data.Description;
        entity.PurchaseOrderId = request.Data.PurchaseOrderId;

        _context.GoodsReceive.Update(entity);

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

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

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