<?php

namespace App\Http\Controllers;

use Illuminate\Broadcasting\BroadcastController as BaseBroadcastController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Broadcast;

class BroadcastController extends BaseBroadcastController
{
    /**
     * Authenticate the request for channel access.
     *
     * This custom implementation supports multi-guard authentication.
     * It uses the active guard from the session to authenticate broadcasting requests.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function authenticate(Request $request)
    {
        // Get the active guard from session (set by SwitchGuardTrait)
        $activeGuard = session('active_guard', 'web');

        // Ensure the user is authenticated on the active guard
        if (!Auth::guard($activeGuard)->check()) {
            abort(403, 'Unauthorized - No active authentication found');
        }

        // Get the authenticated user from the active guard
        $user = Auth::guard($activeGuard)->user();

        // Set the default guard to use for this request
        Auth::shouldUse($activeGuard);

        // Get the channel name from the request
        $channelName = $request->input('channel_name');

        // Attempt to authorize the channel
        try {
            $result = Broadcast::auth($request);

            return response()->json($result);
        } catch (\Exception $e) {
            \Log::error('Broadcasting authentication failed', [
                'guard' => $activeGuard,
                'user_id' => $user->id,
                'channel' => $channelName,
                'error' => $e->getMessage()
            ]);

            abort(403, 'Unauthorized');
        }
    }
}
