<?php

namespace App\Http\Controllers\Owner\GroupProviderReview;

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\GroupProviderReview\Application\Update\UpdateGroupProviderReviewQuery;
use App\Modules\GroupProviderReview\Application\Update\UpdateGroupProviderReviewResponse;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;
use Illuminate\Support\Facades\DB;

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

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

    public function __invoke(Request $request)
    {
        $params = [
            'Id_GroupProviderReview'            => 'required|int',
            'GroupProviderReview_AdminComment'  => 'required|string|max:1000',
        ];
        (new LaravelValidator())->validate($request->all(), 'GroupProviderReview', $params);
        $data = DB::select('call sp_admin_session_get(?,?)', [
            $request->header('Token'),
            $request->ip()
        ])[0];

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

        /** @var UpdateGroupProviderReviewResponse $response */
        $response = $this->queryBus->ask(new UpdateGroupProviderReviewQuery(
            $request->input('Id_GroupProviderReview'),
            $request->input('GroupProviderReview_AdminComment'),
            $data->Response_Id_Admin,
        ));
        $this->history->update(
            $request->input('Id_GroupProviderReview'),
            $this->history->oldValue,
            [],
            $request
        );

        return ResponseBuilder::Response($response->response());
    }
}
