<?php

namespace Shm\ShmChat\ShmChatBlueprints;

use Shm\Shm;
use Shm\ShmAuth\Auth;
use Shm\ShmChat\Exceptions\ChatException;
use Shm\ShmChat\Member;
use Shm\ShmChat\ShmChatService;
use Shm\ShmUtils\I18n;

class ShmChatBlueprintsBaseRPC
{

    public static function accessValidator($channelId)
    {
        Auth::authenticateOrThrow();

        self::runChat(function () use ($channelId) {
            ShmChatService::assertMemberOrJoinable($channelId, Member::fromAuth());
        });
    }

    public static function assertChannelAdmin($channelId): void
    {
        Auth::authenticateOrThrow();

        self::runChat(function () use ($channelId) {
            ShmChatService::assertAdminMember($channelId, Member::fromAuth());
        });
    }

    /**
     * @template T
     * @param callable(): T $callback
     * @return T
     */
    protected static function runChat(callable $callback)
    {
        try {
            return $callback();
        } catch (ChatException $e) {
            Shm::error(I18n::get($e->i18nKey));
        }
    }
}
