<?php

namespace App\Modules\Flight\Application\Insert;

use App\Modules\Booking\Application\Find\FindBookingQuery;
use App\Modules\Booking\Application\Find\FindBookingQueryResponse;
use App\Modules\Flight\Domain\Flight;
use App\Modules\Flight\Domain\FlightRepository;
use App\Modules\Flight\Domain\FlightType;
use App\Modules\Group\Application\Create\CreateGroupQuery;
use App\Modules\Group\Domain\GroupServiceType;
use App\Modules\Group\Domain\GroupType;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;

final class FlightInserter
{
    public function __construct(
        private FlightRepository $repository,
        private QueryBus $queryBus
    ) {}

    public function __invoke(Flight $flight)
    {
        /** @var FindBookingQueryResponse $response */
        $response = $this->queryBus->ask(new FindBookingQuery($flight->idBooking()->value()));

        $idFlight = $this->repository->insert($flight)->__invoke($response);
        $serviceType = $flight->type()->value() === FlightType::TRANSFER_IN ? GroupServiceType::TRANSFER_IN : GroupServiceType::TRANSFER_OUT;
        $this->queryBus->ask(new CreateGroupQuery(
            date('Y-m-d'),
            date('H:i:s'),
            '',
            '',
            GroupType::SHARED,
            '',
            $serviceType,
            $idFlight->value(),
        ));
        return $this->repository->insert($flight);
    }
}
