<?php

namespace Velis\Notification;

use Psr\SimpleCache\InvalidArgumentException;
use ReflectionException;
use Velis\App;
use Velis\Exception;
use Velis\Model\BaseModel;

/**
 * Mobile notification base
 *
 * @author Paweł Szołucha <pawel.szolucha@velistech.com>
 */
abstract class MobileNotification extends BaseModel
{
    protected $params;
    protected $recipient;

    public function setParams(array $params = [])
    {
        $this->params = $params;
    }

    public function setRecipient($recipient)
    {
        $this->recipient = $recipient;
    }

    /**
     * Sends FCM message
     * @return void
     * @throws InvalidArgumentException
     * @throws ReflectionException
     * @throws Exception
     */
    public function send()
    {
        if (App::$config->fcm->pushNotification && isset($this->recipient)) {
            MobileQueue::send($this->prepareMessage());
            unset($this->recipient);
        }
    }

    /**
     * Prepares FCM message
     * @return array
     */
    protected function prepareMessage(): array
    {
        $message = [];

        if (isset($this->params['notification'])) {
            $message['notification'] = $this->params['notification'];
        }

        $message['data'] = $this->params['data'] ?: [];
        $message['topic'] = $this->recipient;

        if (isset($this->params['apns'])) {
            $message['apns'] = $this->params['apns'];
        }

        return $message;
    }
}
