<?php

namespace Shm\ShmChat\ShmChatBlueprints;

use Shm\Shm;
use Shm\ShmAuth\Auth;
use Shm\ShmChat\Classes\ChatMember;
use Shm\ShmChat\Exceptions\ChatException;
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, ChatMember::fromAuth());
        });
    }

    /**
     * @param array<int, string> $roles
     */
    public static function assertChannelMemberWithRoles($channelId, array $roles): void
    {
        Auth::authenticateOrThrow();

        self::runChat(function () use ($channelId, $roles) {
            ShmChatService::assertMemberWithRoles($channelId, ChatMember::fromAuth(), $roles);
        });
    }

    /**
     * @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));
        }
    }
}
