<?php

namespace App\Modules\Cache\Domain;

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

class ExistsCache implements StorageCriteria
{

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

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

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

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

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