<?php

namespace App\Modules\BookingTourPassenger\Application\Cancel;

use App\Modules\BookingTour\Domain\BookingTourRepository;
use App\Modules\BookingTour\Domain\IndexBookingTour;
use App\Modules\BookingTourPassenger\Domain\BookingTourPassenger;
use App\Modules\BookingTourPassenger\Domain\BookingTourPassengerRepository;
use App\Modules\BookingTourPassenger\Domain\BookingTourPassengerStatus;
use App\Modules\BookingTourPassenger\Domain\FromGroupBookingTourPassenger;
use App\Modules\BookingTourPassenger\Domain\IdBookingTourPassenger;
use App\Modules\BookingTourPassenger\Domain\IndexBookingTourPassenger;

final class BookingTourPassengerCanceller
{
    public function __construct(
        private BookingTourPassengerRepository $repository,
        private BookingTourRepository $btRepository
    ) {
    }

    public function __invoke(
        IdBookingTourPassenger $id,
    ): CancelBookingTourPassengerResponse {
        // $model = $this->repository->find(new IndexBookingTourPassenger($id));
        // $model->remove();
        // $this->repository->update($model);

        // $bookingTour = $this->btRepository->find(new IndexBookingTour($model->idBookingTour()));
        // $this->repository->find(new FromGroupBookingTourPassenger($bookingTour->group(), $model->idPassenger()));

        return new CancelBookingTourPassengerResponse($this->repository->cancel($id));
    }

    private function index(IdBookingTourPassenger $id)
    {
        return $this->repository->find(new IndexBookingTourPassenger($id));
    }

    private function removeBookingTourPassenger(BookingTourPassenger $model)
    {
        $model->remove();
        $this->repository->update($model);
    }

    private function removeReceipt(BookingTourPassenger $model, bool $removeReceipt)
    {
        if (!$removeReceipt) {
            return;
        }
        $bookingTour = $this->btRepository->find(new IndexBookingTour($model->idBookingTour()));
        $group = $this->repository->search(new FromGroupBookingTourPassenger($bookingTour->group(), $model->idPassenger()));
        
        if (!$this->isAllGroupStatus($group, new BookingTourPassengerStatus(BookingTourPassengerStatus::CANCELLED))) {
            return;
        }
        
    }

    /**
     * @param array<BookingTourPassenger> $group
     */
    private function isAllGroupStatus(
        array $group,
        BookingTourPassengerStatus $status
    )
    {
        return array_reduce($group, fn($last, BookingTourPassenger $btp) => $last && $btp->status()->value() == $status->value(), true);
    }
}
