<?php

namespace App\Modules\BookingExtra\Application\CopyRoom;

use App\Modules\Admin\Domain\IdAdmin;
use App\Modules\Booking\Application\Find\FindBookingQuery;
use App\Modules\Booking\Domain\IdBooking;
use App\Modules\BookingExtra\Application\Find\BookingExtraFinder;
use App\Modules\BookingExtra\Application\ListByBooking\BookingExtraByBookingLister;
use App\Modules\BookingExtra\Domain\IdBookingExtra;
use App\Modules\BookingTour\Application\Find\FindBookingTourQuery;
use App\Modules\BookingTour\Application\Find\FindBookingTourResponse;
use App\Modules\Room\Application\Copy\CopyRoomQuery;
use App\Modules\Room\Application\List\ListRoomQuery;
use App\Modules\Room\Application\RoomResponses;
use App\Modules\Room\Application\Update\UpdateRoomQueryResponse;
use App\Modules\Room\Domain\ListRoom;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;

final class BookingExtraRoomCopier
{
    private const TYPE_EXTRA_HOTEL = 4;
    public function __construct(
        private QueryBus $queryBus,
        private BookingExtraFinder $bookingExtraFinder,
        private BookingExtraByBookingLister $bookingExtraByBookingLister
    ) {}

    public function __invoke(
        IdBookingExtra $id,
        IdAdmin $idAdmin
    ): UpdateRoomQueryResponse {
        $bookingExtra = $this->bookingExtraFinder->__invoke($id);
        /** @var RoomResponses */
        $listRoomResponse = $this->queryBus->ask(new ListRoomQuery('all', $id->value()));
        /** @var FindBookingTourResponse $response */
        $response = $this->queryBus->ask(new FindBookingTourQuery($bookingExtra->idBookingTour()->value()));
        $list = $this->bookingExtraByBookingLister->__invoke(new IdBooking($response->response()[0]->Id_Booking), true, true);

        $filteredList = $this->filterList($list, $id->value(), BookingExtraRoomCopier::TYPE_EXTRA_HOTEL);

        foreach ($listRoomResponse->data() as $roomResponse) {
            foreach ($filteredList as $item) {
                $this->queryBus->ask(new CopyRoomQuery(
                    $roomResponse->Id_Room,
                    $item->Id_BookingExtra,
                    $idAdmin->value()
                ));
            }
        }


        return new UpdateRoomQueryResponse();
    }

    public function filterList($list, $idBookingExtra, $idTypeExtra)
    {
        // Filter the list by idBookingExtra and idTypeExtra
        return array_filter(
            $list,
            function ($item) use ($idBookingExtra, $idTypeExtra) {
                return $item->Id_BookingExtra != $idBookingExtra && $item->Id_TypeExtra == $idTypeExtra;
            }
        );
    }
}
