<?php

namespace onespace\tools\activeApi\components\clients;

use onespace\tools\activeApi\components\clients\base\BaseOneSpaceClient;
use onespace\tools\rabbit\components\Rabbit;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

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

    /**
     * Emit a message to the communications microservice for sending
     */
    public function sendViaRabbit(?array $how, string|array $who, array $what, ?string $when, string $userId, string $siteId): void {
        /** @var Rabbit $rabbit */
        $rabbit = Yii::$app->rabbit;

        $timestamp = time();
        $payload = Json::encode([
            'event' => [
                'type' => 'create',
                'timestamp' => $timestamp,
            ],
            'entity' => [
                'type' => 'sendMessage',
                'message' => [
                    'how' => $how,
                    'who' => $who,
                    'what' => $what,
                    'when' => $when,
                ],
                'sender' => $userId, // User OSID
                'site' => $siteId, // site GUID
            ],
        ]);
        $routingKey = "v1.json.message.send." . $timestamp;


        $rabbit->outboxSendMessage("onespace.system", $payload, $routingKey, timestamp: $timestamp);
    }

    /**
     * Create a new message via API call
     */
    public function sendViaEndpoint(?array $how, string|array $who, array $what, ?string $when, string $userId, string $siteId): bool {
        $response = self::goPost($this->serverUrl() . 'api/v1/add', [
            'message' => [
                'how' => $how,
                'who' => $who,
                'what' => $what,
                'when' => $when,
            ],
            'sender' => $userId,
            'site' => $siteId,
        ]);

        /** @var bool $success */
        $success = ArrayHelper::getValue($response, "data.success", false);
        return $success;
    }

    /**
     * Cancel a specified message if possible
     */
    public function cancel(string $messageId): bool {
        $response = self::goPost($this->serverUrl() . 'api/v1/cancel', ['messageId' => $messageId]);

        /** @var bool $success */
        $success = ArrayHelper::getValue($response, "data.success", false);
        return $success;
    }

    /**
     * Get a specified message
     */
    public function getMessage(string $recipientId): array|false {
        $response = self::goGet($this->serverUrl() . 'api/vi/view?id=' . $recipientId);

        $message = ArrayHelper::getValue($response, "data.message", false);
        return $message;
    }

    /**
     * Get a list of messages for the user
     *
     * @todo    Currently limitted to the last 50. Revamp for gridview data
     */
    public function listMessages(string $osid, ?string $siteId = null): array|false {
        $url = $this->serverUrl() . 'api/vi/view/list?id=' . $osid;
        if ($siteId !== null) {
            $url .= '&siteId=' . $siteId;
        }

        $response = self::goGet($url);

        $message = ArrayHelper::getValue($response, "data.results", false);
        return $message;
    }

    /**
     * Get a message via it's public ID
     */
    public function getMessageViaPublicId(string $publicId): string|false {
        $response = self::goGet($this->serverUrl() . 'api/vi/view/public?id=' . $publicId);

        $message = ArrayHelper::getValue($response, "data", false);
        return $message;
    }
}
