<?php

use App\Models\Project;
use App\Support\AppMode;
use Illuminate\Support\Facades\Broadcast;

/*
|--------------------------------------------------------------------------
| Broadcast Channels (Team Workspaces P6 / Tier 2 — Reverb opt-in)
|--------------------------------------------------------------------------
|
| Channels are only ever subscribed when an operator has flipped the
| `collab.transport` Setting to `reverb` AND is running a persistent
| `php artisan reverb:start` process (SSH/VPS only — never the shared
| default, honoring CLAUDE.md §Don'ts). With the default `lock` transport
| the Echo client never initializes, so this auth callback is dormant.
|
*/

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

/**
 * Per-project presence channel for live concurrent editing. Authorization
 * mirrors the editor's `ScreenController::authorizeProject` exactly — the
 * subscriber must pass the SAME access check that gates the editor itself
 * (tenant scope + per-project visibility grant in SaaS; shared-pool null
 * tenant in self-hosted). A presence channel returns the member identity so
 * peers can render presence; returning false/null rejects the subscription.
 */
Broadcast::channel('project.{projectId}', function ($user, $projectId): array|bool {
    $project = Project::find((int) $projectId);
    if ($project === null) {
        return false;
    }

    if (AppMode::isSelfHosted()) {
        if ($project->tenant_id !== null) {
            return false;
        }
    } else {
        if ($project->tenant_id !== $user->tenant_id) {
            return false;
        }
        if (! $user->canAccessProject($project)) {
            return false;
        }
    }

    // Presence channel member payload (id + name) so peers can show who's in.
    return ['id' => $user->id, 'name' => $user->name];
});
