<?php

namespace App\Http\Controllers\Owner\BookingEquipment;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Owner\BookingEquipment\Dto\BookingEquipmentUpdatePartialDTO;
use App\Http\Helpers\ResponseBuilder;
use App\Http\History\HistoryData;
use App\Http\History\HistoryTables;
use App\Modules\BookingEquipment\Application\UpdatePartial\UpdatePartialBookingEquipmentQuery;
use App\Modules\BookingEquipment\Application\UpdatePartial\UpdatePartialBookingEquipmentResponse;
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 BookingEquipmentUpdatePartialController extends Controller
{
    private $domain;
    private HistoryData $history;

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

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

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

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

        /** @var UpdatePartialBookingEquipmentResponse $update */
        $update = $this->queryBus->ask(new UpdatePartialBookingEquipmentQuery(
            id: $dto->Id_BookingEquipment,
            show: $dto->BookingEquipment_Show,
            included: $dto->BookingEquipment_Included,
            mode: $dto->BookingEquipment_Mode,
        ));

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

        $this->history->update(
            $this->findBooking($dto->Id_BookingEquipment),
            $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"     => '',
        ]);
    }
}
