<?php

namespace Shm\ShmIntegrations\PWA;


use Shm\Shm;
use Shm\ShmAuth\Auth;
use Shm\ShmDB\mDB;
use Shm\ShmRPC\ShmRPC;
use Minishlink\WebPush\VAPID;
use Minishlink\WebPush\WebPush;

use Minishlink\WebPush\Subscription;

class PWAPush
{




    private static function getPublicKey(string $_appKey)
    {

        //Проверка есть ли в базе appKey
        $data = mDB::collection("_pwaPushApps")->findOne([
            'appKey' => $_appKey,
        ]);

        if (!$data) {

            $keys = VAPID::createVapidKeys();
            mDB::collection("_pwaPushApps")->insertOne([
                'appKey' => $_appKey,
                'publicKey' => $keys['publicKey'],
                'privateKey' => $keys['privateKey'],
            ]);

            return $keys['publicKey'];
        }

        return $data['publicKey'];
    }

    public static function rpc(string $appKey)
    {

        return [

            "pwaPushSubscription"  => ShmRPC::lazy(function () use ($appKey) {
                return [
                    'type' => Shm::bool(),
                    'args' => [
                        'endpoint' => Shm::string(),
                        'expirationTime' => Shm::int(),
                        'keys' => Shm::structure([
                            'p256dh' => Shm::string(),
                            'auth' => Shm::string(),
                        ]),
                    ],
                    'resolve' => function ($root, $args) use ($appKey) {



                        mDB::collection("_pwaPushSubscriptions")->updateOne([
                            'endpoint' => $args['endpoint'],
                            'owner' => Auth::getAuthID(),
                            'ownerCollection' => Auth::getAuthCollection(),
                            'appKey' => $appKey,
                        ], [
                            '$set' => [
                                'endpoint' => $args['endpoint'],
                                'expirationTime' => $args['expirationTime'] ?? null,
                                'keys' => $args['keys'],
                                'owner' => Auth::getAuthID(),
                                'ownerCollection' => Auth::getAuthCollection(),
                                'appKey' => $appKey,
                            ],
                        ], [
                            'upsert' => true,
                        ]);

                        return true;
                    },
                ];
            }),
            "pwaPushPublicKey" => ShmRPC::lazy(function () use ($appKey) {
                return [
                    'type' => Shm::string(),
                    'resolve' => function () use ($appKey) {
                        return self::getPublicKey($appKey);
                    },
                ];
            }),

        ];
    }
}
