<?php

use App\Models\Admin;
use App\Models\ChatSession;
use App\Models\Client;
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;
});

Broadcast::channel('chat.{sessionId}', function ($user, $sessionId) {
    $session = ChatSession::find($sessionId);
    if (! $session) {
        return false;
    }

    if ($user instanceof Admin) {
        // PRC-187 + PRC-608: view tickets olan HER admin görüşmeyi görebilir
        // (view-all). Yanıtlama yetkisi assignment ile Admin\ChatController::send'de
        // gate'lenir — kanal yalnız okuma/dinleme içindir.
        if (! $user->can('view tickets')) {
            return false;
        }
        return ['id' => 'admin-' . $user->id, 'name' => $user->name ?? 'Admin'];
    }

    if ($user instanceof Client) {
        $activeClientId = (int) (session('active_client_id') ?? $user->id);
        if ((int) $session->client_id === $activeClientId) {
            return ['id' => 'client-' . $user->id, 'name' => $session->visitor_name];
        }
    }

    return false;
}, ['guards' => ['admin', 'client']]);

// PRC-607 — Admin canlı destek farkındalık kanalı. YALNIZ içeriksiz sinyal taşır
// (yeni waiting / accept / activity). Mesaj İÇERİĞİ buraya GİRMEZ (PRC-187:
// per-session chat.{id} izolasyonu korunur). view tickets permission gated.
Broadcast::channel('admin.chat', function ($user) {
    return $user instanceof Admin && $user->can('view tickets');
}, ['guards' => ['admin']]);
