<?php

namespace FleekDash\Realtime;

defined('ABSPATH') || exit;

/**
 * Publishes FleekDash realtime envelopes to Supabase Realtime Broadcast (managed transport).
 * Requires {@see FLEEKDASH_SUPABASE_SERVICE_ROLE_KEY} in wp-config.php (never commit this value).
 */
class SupabaseRealtimePublisher
{
    private const BROADCAST_EVENT = 'fd_envelope';

    private const CHANNEL_PREFIX = 'fleekdash_';

    private const BROADCAST_PATH = '/realtime/v1/api/broadcast';

    public static function isConfigured(): bool
    {
        return self::getServiceRoleKey() !== '';
    }

    public static function broadcast(string $tenantId, array $envelope): bool
    {
        $result = false;
        $key = self::getServiceRoleKey();
        $baseUrl = self::getSupabaseBaseUrl();
        $topic = self::channelNameForTenant($tenantId);
        $canSend = $key !== '' && $baseUrl !== '' && $topic !== '';

        if ($canSend) {
            $url = rtrim($baseUrl, '/') . self::BROADCAST_PATH;
            $body = \wp_json_encode([
                'messages' => [
                    [
                        'topic' => $topic,
                        'event' => self::BROADCAST_EVENT,
                        'payload' => $envelope,
                    ],
                ],
            ]);
            $response = \wp_remote_post($url, [
                'headers' => [
                    'apikey' => $key,
                    'Authorization' => 'Bearer ' . $key,
                    'Content-Type' => 'application/json',
                ],
                'timeout' => 10,
                'body' => is_string($body) ? $body : '{}',
            ]);
            $result = self::isSuccessResponse($response);
        }

        return $result;
    }

    public static function channelNameForTenant(string $tenantId): string
    {
        $safe = preg_replace('/[^a-f0-9]/', '', strtolower($tenantId)) ?? '';

        return $safe === '' ? '' : self::CHANNEL_PREFIX . $safe;
    }

    private static function getServiceRoleKey(): string
    {
        if (!defined('FLEEKDASH_SUPABASE_SERVICE_ROLE_KEY')) {
            return '';
        }
        $key = \constant('FLEEKDASH_SUPABASE_SERVICE_ROLE_KEY');

        return is_string($key) ? trim($key) : '';
    }

    private static function getSupabaseBaseUrl(): string
    {
        if (!defined('FLEEKDASH_SUPABASE_URL')) {
            return '';
        }
        $url = \constant('FLEEKDASH_SUPABASE_URL');

        return is_string($url) ? trim($url) : '';
    }

    /**
     * @param array|\WP_Error $response
     */
    private static function isSuccessResponse($response): bool
    {
        $ok = false;
        if (!\is_wp_error($response)) {
            $code = (int) \wp_remote_retrieve_response_code($response);
            $ok = $code >= 200 && $code < 300;
        }

        return $ok;
    }
}
