<?php

namespace App\Modules\Template\TourTemplate\Domain;

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

class ExistsTourTemplate implements StorageCriteria
{

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

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

    protected function query()
    {
        $select = TourTemplate::select('`r`');
        $table = TourTemplate::table();

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

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