<?php

namespace App\Modules\ExternalApiRequest\Domain;

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

class IndexExternalApiRequest implements StorageCriteria
{

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

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

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

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

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