<?php

namespace App\Modules\HtlCampLock\Domain;

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

class IndexHtlCampLock implements StorageCriteria
{

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

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

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

        return DB::select(
            "SELECT $select
            FROM `t_htl_camp_lock` `hcl`
            WHERE `hcl`.`Id_HtlCampLock` = ?
            AND `hcl`.`HtlCampLock_Status` > 0
            $lockInShare",
            [
                $this->id->value()
            ]
        );
    }

    protected function analize($data)
    {
        if (!count($data)) {
            throw new HtlCampLockNotFound();
        }
        return $data[0];
    }
}
