<?php

namespace App\Http\Controllers\Owner\Room;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Owner\c_Admin_Session;
use App\Http\Controllers\Owner\Room\Dto\RoomUpdateDTO;
use Illuminate\Http\Request;
use App\Http\Helpers\ResponseBuilder;
use App\Http\History\HistoryTables;
use App\Modules\History\Application\Insert\InsertHistoryQuery;
use App\Modules\History\Domain\HistoryOperation;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Validator\Infraestructure\LaravelDTOGenerator;
use App\Modules\Room\Application\Index\IndexRoomQuery;
use App\Modules\Room\Application\RoomResponse;
use App\Modules\Room\Application\Update\UpdateRoomQuery;
use App\Modules\Room\Application\Update\UpdateRoomQueryResponse;

class RoomUpdateController extends Controller
{
    private $domain;

    public function __construct(
        private QueryBus $queryBus,
        private LaravelDTOGenerator $dtoGenerator,
    ) {
        $this->domain = "Room";
    }

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

        /** @var RoomResponse $firstResponse */
        $firstResponse = $this->queryBus->ask(new IndexRoomQuery($dto->Id_Room, ''));

        /** @var UpdateRoomQueryResponse $response */
        $this->queryBus->ask(new UpdateRoomQuery(
            $dto->Id_Room,
            $dto->Room_RequestDateStart,
            $dto->Room_RequestDateEnd,
            $dto->Room_ReservationDateFinal,
            $dto->Room_Observation,
            $dto->Room_BuyPrice,
            $dto->Room_BuyCode,
            $dto->Room_Status,
            $dto->Id_TypeRoom,
            $dto->Id_Provider,
            $dto->Id_TypePayment,
            $dto->Room_DateChanged,
            $adminSession['Id_Admin'],
        ));

        /** @var RoomResponse $lastResponse */
        $lastResponse = $this->queryBus->ask(new IndexRoomQuery($dto->Id_Room, ''));

        $this->queryBus->ask(new InsertHistoryQuery(
            json_encode($firstResponse),
            json_encode($lastResponse),
            HistoryOperation::UPDATE,
            $dto->Id_Room,
            $dto->Id_Room,
            HistoryTables::room,
            $adminSession['Id_Admin'],
        ));

        $oResponse = [];
        $oResponse["Response_Status"]           = 200;
        $oResponse["Response_Code"]             = 200;
        $oResponse["Response_Domain"]           = $this->domain;
        $oResponse["Response_Message"]          = 'Actualizado con éxito';
        $oResponse["Response_Data"]             = null;
        $oResponse["Response_Error_Message"]    = '';
        $oResponse["Response_Error_Reason"]     = '';
        return ResponseBuilder::Response($oResponse);
    }
}
