<?php

namespace App\Http\Controllers\Owner\HtlCampBookingPassenger;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Helpers\ResponseBuilder;
use App\Http\History\HistoryData;
use App\Http\History\HistoryTables;
use App\Modules\HtlCampBookingPassenger\Application\Create\CreateHtlCampBookingPassengerQuery;
use App\Modules\HtlCampBookingPassenger\Application\Create\CreateHtlCampBookingPassengerResponse;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;
use App\Modules\HtlCampBookingPassenger\Infrastructure\HtlCampBookingPassengerValidators;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Domain\Transaction;

class HtlCampBookingPassengerInsertController extends Controller
{
    private $domain;
    private HistoryData $history;

    public function __construct(
        private QueryBus $queryBus,
        private Transaction $transaction
    ) {
        $this->domain = "HtlCampBookingPassenger";
        $this->history = new HistoryData(HistoryTables::HTL_CAMP_BOOKING_PASSENGER);
    }

    public function __invoke(Request $request)
    {
        (new LaravelValidator())->validate(
            $request->all(),
            $this->domain,
            HtlCampBookingPassengerValidators::INSERT
        );
        $this->transaction->begin();

        $passengers = $request->input('Passengers');

        $responses = [];
        foreach ($passengers as $passenger) {
            /** @var CreateHtlCampBookingPassengerResponse $response */
            $response = $this->queryBus->ask(new CreateHtlCampBookingPassengerQuery(
                $passenger['HtlCampBookingPassenger_Weight'],
                $passenger['HtlCampBookingPassenger_Status'],
                $request->input('Id_HtlCampBooking'),
                $passenger['Id_BookingTourPassenger'],
            ));
            $responses[] = $response;
        }

        $this->transaction->commit();
        foreach ($responses as $response) {
            $this->history->insertBasic($request, $response->id());
        }

        return ResponseBuilder::Response([
            "Response_Status"           => 200,
            "Response_Code"             => 200,
            "Response_Data"             => ['id' => $response->id()],
            "Response_Domain"           => $this->domain,
            "Response_Message"          => 'Reserva de campamento agregada con éxito',
            "Response_Error_Message"    => '',
            "Response_Error_Reason"     => '',
        ]);
    }
}
