<?php

namespace App\Http\Controllers\Owner\Tour;

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\Tour\Application\Create\TourInserterQuery;
use App\Modules\Tour\Application\Create\TourInserterResponse;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;
use App\Modules\Tour\Infraestructure\TourValidators;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Tour\Application\List\ListTourQuery;
use App\Modules\Tour\Application\List\ListTourResponses;
use Illuminate\Support\Str;

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

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

    public function transformInput($input)
    {
        return [
            'List' => $input['List'],
            'TypeTour' => array_map(fn($k) => trim($k), explode(',', $input['TypeTour'])),
            'CategoryTour' => array_map(fn($k) => trim($k), explode(',', $input['CategoryTour'])),
            'Aggregation' => array_map(fn($k) => trim($k), explode(',', $input['Aggregation'])),
            'Page' => $input['Page'] ?? null,
            'PageSize' => $input['PageSize'] ?? null
        ];
    }

    public function __invoke(Request $request)
    {
        (new LaravelValidator())->validate($request->all(), $this->domain, TourValidators::LIST);
        $input = $this->transformInput($request->all());
        (new LaravelValidator())->validate($input, $this->domain, TourValidators::LIST_EXPLODED);

        /** @var ListTourResponses $response */
        $response = $this->queryBus->ask(new ListTourQuery(
            $input['List'],
            $input['TypeTour'],
            $input['CategoryTour'],
            $input['Aggregation'],
            $input['Page'],
            $input['PageSize'],
        ));

        return ResponseBuilder::Response(ResponseBuilder::buildSelectResponse($response->data(), '', $this->domain));
    }
}
