<?php

namespace onespace\tools\activeApi\components\clients;

use onespace\tools\activeApi\components\clients\base\BaseOneSpaceClient;
use Yii;

/**
 * The client to connect to the VMS4 Microservice
 *
 * Extend from here to add functionality.
 *
 * Add the following to `config/params.php`:
 *
 * ```php
 * 'serviceUrls' => [
 *  ...
 *  'vms4' => getenv('SERVICE_URL_VMS4') ?: 'https://dev.visit.1s.co.za/',
 *  ...
 * ],
 * ```
 */

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

    public function getVisits(): array|false {
        $url = $this->serverUrl() . 'api/v1/visit';
        Yii::info($url, __METHOD__);

        $request = $this->getClient()->get($url);

        $this->setLastRequest($request);
        $response = $request->send();
        if ($response->isOk) {
            return $response->data['data'];
        }
        Yii::error("Request failed...", __METHOD__);
        Yii::warning($response->content, __METHOD__);
        return false;
    }

    public function createVisit(array $data, $fullResponse = false): array|false {

        $url = $this->serverUrl() . 'api/v1/visit/create';

        $request = $this->getClient()->post($url, $data);

        $this->setLastRequest($request);
        $response = $request->send();

        if ($fullResponse) {
            return $response->getData();
        }

        if ($response->isOk) {
            return $response->data['data'];
        }

        Yii::error("Request failed...", __METHOD__);
        Yii::warning(json_encode($response->data), __METHOD__);

        return false;
    }

    /**
     * @param string $visitId Visit GUID
     * @param string $cancellingUserId Cancelling User GUID
     */
    public function cancelVisit(string $visitId, string $cancellingUserId): array|false {
        $url = $this->serverUrl() . 'api/v1/visit/cancel';

        $request = $this->getClient()->post($url, [
            'visit' => $visitId,
            'user' => $cancellingUserId,
        ]);

        $this->setLastRequest($request);
        $response = $request->send();
        if ($response->isOk) {
            return $response->data['data'];
        }
        Yii::error("Request failed...", __METHOD__);
        Yii::warning($response->content, __METHOD__);
        return false;
    }
}
