<?php

namespace App\Modules\DefinedService\Route\Domain;

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

class ExistsRoute implements StorageCriteria
{

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

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

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

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

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