<?php

namespace App\Http\Controllers\Owner\BookingUpgrade;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Owner\BookingUpgrade\Dto\BookingUpgradeUpdatePartialDTO;
use App\Http\Helpers\ResponseBuilder;
use App\Http\History\HistoryData;
use App\Http\History\HistoryTables;
use App\Modules\BookingUpgrade\Application\UpdatePartial\UpdatePartialBookingUpgradeQuery;
use App\Modules\BookingUpgrade\Application\UpdatePartial\UpdatePartialBookingUpgradeResponse;
use App\Modules\Shared\Domain\Bus\Command\CommandBus;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Validator\Infraestructure\LaravelDTOGenerator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

final class BookingUpgradeUpdatePartialController extends Controller
{
    private $domain;
    private HistoryData $history;

    public function __construct(
        private CommandBus $commandBus,
        private QueryBus $queryBus,
        private LaravelDTOGenerator $dtoGenerator
    ) {
        $this->domain = "BookingUpgrade";
        $this->history = new HistoryData(HistoryTables::BOOKING_EXTRA);
    }

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

    public function __invoke(Request $request)
    {
        /** @var BookingUpgradeUpdatePartialDTO $dto */
        $dto = $this->dtoGenerator->generate($request->all(), $this->domain, BookingUpgradeUpdatePartialDTO::class);

        $this->history->obtainOld($dto->Id_BookingUpgrade);

        /** @var UpdatePartialBookingUpgradeResponse $update */
        $update = $this->queryBus->ask(new UpdatePartialBookingUpgradeQuery(
            id: $dto->Id_BookingUpgrade,
            show: $dto->BookingUpgrade_Show,
            included: $dto->BookingUpgrade_Included,
            mode: $dto->BookingUpgrade_Mode,
        ));

        $this->history->obtainNew($dto->Id_BookingUpgrade);

        $this->history->update(
            $this->findBooking($dto->Id_BookingUpgrade),
            $this->history->oldValue,
            $this->history->newValueCache,
            $request
        );
        return ResponseBuilder::Response([
            "Response_Status"           => 200,
            "Response_Code"             => 200,
            "Response_Data"             => [],
            "Response_Domain"           => $this->domain,
            "Response_Message"          => 'Servicio de tour modificado con éxito',
            "Response_Error_Message"    => '',
            "Response_Error_Reason"     => '',
        ]);
    }
}
