<?php

namespace FleekDash\Controllers;

use FleekDash\Realtime\RealtimeConfig;
use FleekDash\Realtime\RealtimeEventOutboxService;

defined('ABSPATH') || exit;

class RealtimeController
{
    public function getConfig(\WP_REST_Request $_request): \WP_REST_Response // NOSONAR php:S1172 - WP REST callback signature
    {
        $userId = \get_current_user_id();
        if ($userId <= 0) {
            return new \WP_REST_Response([
                'success' => true,
                'realtime' => [
                    'enabled' => false,
                ],
            ], 200);
        }

        $token = \wp_create_nonce('fleekdash_realtime_' . $userId);
        $provider = RealtimeConfig::getProvider();
        $transport = $provider === 'managed' ? 'supabase' : 'websocket';
        $supabaseUrl = defined('FLEEKDASH_SUPABASE_URL') ? (string) \FLEEKDASH_SUPABASE_URL : '';
        $supabaseAnonKey = defined('FLEEKDASH_SUPABASE_KEY') ? (string) \FLEEKDASH_SUPABASE_KEY : '';

        return new \WP_REST_Response([
            'success' => true,
            'realtime' => [
                'enabled' => RealtimeConfig::isEnabled(),
                'transport' => $transport,
                'url' => $provider === 'managed' ? '' : RealtimeConfig::getWsUrl(),
                'supabaseUrl' => $supabaseUrl,
                'supabaseAnonKey' => $supabaseAnonKey,
                'token' => $token,
                'tenantId' => RealtimeConfig::getTenantId(),
                'userId' => $userId,
                'maxSubscriptionsPerClient' => RealtimeConfig::getMaxSubscriptionsPerClient(),
                'maxPayloadBytes' => RealtimeConfig::getMaxPayloadBytes(),
                'killSwitch' => RealtimeConfig::isKillSwitchEnabled(),
                'rolloutCohort' => RealtimeConfig::getRolloutCohort(),
            ],
        ], 200);
    }

    public function dispatchOutbox(\WP_REST_Request $_request): \WP_REST_Response // NOSONAR php:S1172 - WP REST callback signature
    {
        RealtimeEventOutboxService::dispatchPendingEvents();
        return new \WP_REST_Response([
            'success' => true,
        ], 200);
    }

    public function getStats(\WP_REST_Request $_request): \WP_REST_Response // NOSONAR php:S1172 - WP REST callback signature
    {
        return new \WP_REST_Response([
            'success' => true,
            'stats' => RealtimeEventOutboxService::getStats(),
        ], 200);
    }

    public function updateConfig(\WP_REST_Request $request): \WP_REST_Response
    {
        $enabled = (bool) $request->get_param('enabled');
        $cohortFromRequest = (string) ($request->get_param('rollout_cohort') ?: 'off');
        $rolloutCohort = $enabled ? $cohortFromRequest : 'off';
        $settings = [
            'fleekdash_realtime_enabled' => $enabled,
            'fleekdash_realtime_killswitch' => (bool) $request->get_param('kill_switch'),
            'fleekdash_realtime_rollout_cohort' => $rolloutCohort,
            'fleekdash_realtime_max_subscriptions' => (int) ($request->get_param('max_subscriptions') ?: RealtimeConfig::DEFAULT_MAX_SUBSCRIPTIONS),
            'fleekdash_realtime_max_payload_bytes' => (int) ($request->get_param('max_payload_bytes') ?: RealtimeConfig::DEFAULT_MAX_PAYLOAD_BYTES),
            'fleekdash_realtime_publish_rate_limit_per_minute' => (int) ($request->get_param('publish_rate_limit_per_minute') ?: RealtimeConfig::DEFAULT_RATE_LIMIT_PER_MINUTE),
            'fleekdash_realtime_provider' => (string) ($request->get_param('provider') ?: 'managed'),
            'fleekdash_realtime_ws_url' => (string) ($request->get_param('ws_url') ?: ''),
            'fleekdash_realtime_publish_endpoint' => (string) ($request->get_param('relay_endpoint') ?: ''),
            'fleekdash_realtime_publish_token' => (string) ($request->get_param('relay_token') ?: ''),
        ];

        foreach ($settings as $key => $value) {
            \update_option($key, $value);
        }

        return new \WP_REST_Response([
            'success' => true,
        ], 200);
    }

    public function testEvent(\WP_REST_Request $_request): \WP_REST_Response // NOSONAR php:S1172 - WP REST callback signature
    {
        $userId = \get_current_user_id();
        if ($userId <= 0) {
            return new \WP_REST_Response([
                'success' => false,
                'message' => 'User not authenticated.',
            ], 401);
        }

        RealtimeEventOutboxService::emitNotificationCreated(
            $userId,
            'Realtime test event delivered successfully.',
            ['source' => 'settings-test-event']
        );
        RealtimeEventOutboxService::dispatchPendingEvents();

        return new \WP_REST_Response([
            'success' => true,
        ], 200);
    }
}

