<?php

namespace App\Modules\Leads\WebPage\Domain;

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

class ExistsWebPage implements StorageCriteria
{

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

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

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

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

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