<?php

namespace Myvetshop\Module\Clinique\Accounting\Export\Bulk;

class BulkDocumentProcessor
{
    protected BulkExportContext $bulkExportContext;
    protected BulkDocumentOrderAssociator $bulkDocumentOrderAssociator;

    public function __construct(
        BulkExportContext $bulkExportContext,
        BulkDocumentOrderAssociator $bulkDocumentOrderAssociator
    ) {
        $this->bulkExportContext = $bulkExportContext;
        $this->bulkDocumentOrderAssociator = $bulkDocumentOrderAssociator;
    }

    /**
     * @template T of \OrderInvoice|\OrderSlip
     *
     * @param T[] $documents
     * @param \Order[] $orders
     *
     * @return \Generator<array{0: T, 1: \Order}>
     */
    public function processChunk(
        array $documents,
        array $orders
    ): \Generator {
        if (empty($documents) || empty($orders)) {
            return;
        }

        // Begin bulk processing
        $this->bulkExportContext->preload($orders);

        $documentsWithOrders = $this->bulkDocumentOrderAssociator->associate($documents, $orders);

        foreach ($documentsWithOrders as $documentsWithOrder) {
            yield $documentsWithOrder;
        }

        // Ends bulk processing
        $this->bulkExportContext->clear();
    }
}
