<?php

namespace onespace\tools\activeApi\components\clients;

use onespace\tools\activeApi\components\clients\base\BaseOneSpaceClient;
use Yii;
use yii\web\NotFoundHttpException;

class FactoryClient extends BaseOneSpaceClient {
    public function serverUrl(): string {
        return Yii::$app->params['serviceUrls']['factory'];
    }

    public function fetchListByType(string $search, string $type): array {
        $url = $this->serverUrl() . "v2/factory/list-by-type?" . http_build_query([
            's' => $search,
            't' => $type,
        ]);
        Yii::info($url, __METHOD__);

        $request = $this->getClient()->get($url);
        $this->setLastRequest($request);
        $response = $request->send();
        if (!$response->isOk) {
            Yii::error($response->data, __METHOD__);
            throw new NotFoundHttpException("Cannot fetch linked devices and groups");
        }
        return $response->data['data'];
    }

    public function searchEntries(string $search, string $type): array {
        $search = trim($search);
        $search = stripslashes($search);
        $search = htmlspecialchars($search, ENT_QUOTES);
        $search = urlencode($search);

        $url = $this->serverUrl() . 'v2/factory/search?' . http_build_query([
            's' => $search,
            't' => $type,
        ]);
        Yii::info($url, __METHOD__);

        $request = $this->getClient()->get($url);
        $this->setLastRequest($request);
        $response = $request->send();
        if (!$response->isOk) {
            Yii::error($response->data, __METHOD__);
            throw new NotFoundHttpException("Cannot fetch linked devices and groups");
        }
        Yii::debug($response->data, __METHOD__);
        return $response->data['data'];
    }
}
