<?php

use Illuminate\Support\Facades\Broadcast;

/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/

Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

// Chat channel authorization
Broadcast::channel('private-chat.{conversationId}', function ($auth, $conversationId) {
    $conversation = \App\Models\Conversation::find($conversationId);
    if (!$conversation) {
        return false;
    }

    // Determine auth actor type
    $authType = $auth instanceof \App\Models\EmpCompanyDetails ? 'emp' : 'user';
    $authId = $auth->id;

    $isP1 = $conversation->participant1_id == $authId && $conversation->participant1_type === $authType;
    $isP2 = $conversation->participant2_id == $authId && $conversation->participant2_type === $authType;
    return $isP1 || $isP2;
});

// Presence channel for online status - users can only join their own presence channel
Broadcast::channel('presence-user.{userId}', function ($auth, $userId) {
    return (int) $auth->id === (int) $userId;
});

// Presence channel for employees - employees can only join their own presence channel
Broadcast::channel('presence-emp.{empId}', function ($auth, $empId) {
    return $auth instanceof \App\Models\EmpCompanyDetails && (int) $auth->id === (int) $empId;
});

// Global presence channel for all users in a workspace
Broadcast::channel('presence-workspace.{workspaceId}', function ($auth, $workspaceId) {
    // Check if user belongs to this workspace
    if ($auth instanceof \App\Models\EmpCompanyDetails) {
        return $auth->workspace_id == $workspaceId;
    } elseif ($auth instanceof \App\Models\User) {
        return $auth->current_workspace_id == $workspaceId;
    }
    return false;
});

// Personal notification channels for users
Broadcast::channel('private-user.{userId}', function ($auth, $userId) {
    return (int) $auth->id === (int) $userId;
});

// Personal notification channels for employees
Broadcast::channel('private-emp.{empId}', function ($auth, $empId) {
    return $auth instanceof \App\Models\EmpCompanyDetails && (int) $auth->id === (int) $empId;
});