<?php

namespace App\Modules\TypeRoom\Domain;

use App\Modules\Shared\Domain\Storage\Criteria\StorageCriteria;
use Illuminate\Support\Facades\DB;

class ExistsTypeRoom implements StorageCriteria
{

    public function __construct(
        private IdTypeRoom $id,
        private bool $lockInShare = false
    ) {}

    public function run()
    {
        return $this->analize($this->query());
    }

    protected function query()
    {
        $select = TypeRoom::select('`r`');
        $table = TypeRoom::table();
        $lockInShare = $this->lockInShare ? ' LOCK IN SHARE MODE' : '';

        return DB::select(
            "SELECT $select
            FROM `$table` `r`
            WHERE `r`.`Id_TypeRoom` = ?
            $lockInShare",
            [
                $this->id->value()
            ]
        );
    }

    protected function analize($data)
    {
        if (!count($data)) {
            throw new TypeRoomNotExists();
        }
        return TypeRoom::fromDTO($data[0]);
    }
}
