<?php

namespace App\Services\Chat;

use App\Models\ChatSession;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

/**
 * PRC-606 — Chat katılımcısını tek noktada çözer (optional-auth):
 *  - login client → guard'dan (switched-user için active_client_id)
 *  - misafir       → istek token'ından (public_token bearer)
 */
class ChatParticipantResolver
{
    /**
     * @return array{type:string, client_id:?int, token:?string}
     *         type: 'client' | 'guest'
     */
    public function resolve(Request $request): array
    {
        if (Auth::guard('client')->check()) {
            $clientId = (int) (session('active_client_id') ?? Auth::guard('client')->id());

            return ['type' => 'client', 'client_id' => $clientId, 'token' => null];
        }

        return ['type' => 'guest', 'client_id' => null, 'token' => (string) $request->input('token', '')];
    }

    /**
     * Katılımcının bu session'a erişim hakkı var mı?
     *
     * @param  array{type:string, client_id:?int, token:?string}  $participant
     */
    public function authorize(ChatSession $session, array $participant): bool
    {
        if ($participant['type'] === 'client') {
            return $session->client_id !== null
                && (int) $session->client_id === (int) $participant['client_id'];
        }

        return $session->client_id === null
            && $session->public_token !== null
            && $participant['token'] !== ''
            && hash_equals((string) $session->public_token, (string) $participant['token']);
    }
}
