<?php

namespace App\Modules\CashMovementFactReceipt\Application\GenerateProduct;

use App\Modules\FactProduct\Application\Creator\FactProductCreator;
use App\Modules\FactProduct\Domain\IdFactProduct;
use App\Modules\FactReceiptDetail\Application\Create\FactReceiptDetailCreator;
use App\Modules\Shared\Domain\Bus\Query\QueryHandler;

final class GenerateProductCashMovementFactReceiptQueryHandler implements QueryHandler
{
    public function __construct(
        private CashMovementFactReceiptProductGenerator $generator,
        private FactProductCreator $productCreator,
        private FactReceiptDetailCreator $detailCreator
    ) {
    }

    public function __invoke(GenerateProductCashMovementFactReceiptQuery $query)
    {
        $elements = $this->generator->__invoke($query->bookingTourPassenger(), $query->idFactReceipt());

        $generated = array_map(function ($element) {
            $product = $this->productCreator->__invoke($element[0]);
            $idProduct = $product->response()['Response_Data']['Id'];
            $element[1]->setProduct(new IdFactProduct($idProduct));
            $detail = $this->detailCreator->__invoke($element[1], $product);
            return (object)[
                'id' => $detail->response()['Response_Data']['Id']
            ];
        }, $elements);
        return new GenerateProductCashMovementFactReceiptResponse($generated);
    }
}
