<?php

namespace App\Http\Controllers\Owner\GroupProvider;

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\GroupProvider\Application\Mask\MaskGroupProviderQuery;
use App\Modules\GroupProvider\Application\Mask\MaskGroupProviderResponse;
use App\Modules\GroupProvider\Infraestructure\GroupProviderValidators;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;
use Illuminate\Support\Facades\DB;

class GroupProviderMaskController extends Controller
{
    private $domain;
    /** @var HistoryData */
    private $history;

    public function __construct(
        private QueryBus $queryBus
    ) {
        $this->domain = "GroupProvider";
        $this->history = new HistoryData(HistoryTables::GROUP_PROVIDER);
    }

    public static function findBooking($Id_GroupProvider)
    {
        $found = DB::select('SELECT `fn_booking_tour_detail_passenger_find_booking`(?,?) as Id_Booking', [$Id_GroupProvider, 2]);
        return count($found) ? $found[0]->Id_Booking : null;
    }

    public function __invoke(Request $request)
    {
        (new LaravelValidator)->validate($request->all(), 'Booking', GroupProviderValidators::MASK);

        $this->history->obtainOld($request->input('Id_GroupProvider'));

        /** @var MaskGroupProviderResponse $response */
        $response = $this->queryBus->ask(new MaskGroupProviderQuery(
            $request->input('Id_GroupProvider'),
            $request->input('GroupProvider_Mask')
        ));

        $this->history->update($this->findBooking($request->input('Id_GroupProvider')), $this->history->oldValue, [], $request);
        return ResponseBuilder::Response($response->response());
    }
}
