<?php

namespace App\Events;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

/**
 * Fired whenever a new in-app notification is created for a user.
 *
 * Broadcasts on the ORGANISATION channel so all org members receive
 * the websocket frame. The frontend then filters by:
 *  - $userId   (null = broadcasted to all org users, e.g. announcements)
 *  - $roles    (only show to users holding one of these Spatie role names)
 *
 * Both filters may be set; an empty $roles array means "all users".
 */
class NewNotificationCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(
        public readonly int    $organizationId,
        public readonly string $type,
        public readonly string $title,
        public readonly string $body,
        public readonly array  $data,
        /** Specific user this notification belongs to (null = role-based) */
        public readonly ?int   $userId  = null,
        /** Spatie role names that should receive this notification */
        public readonly array  $roles   = [],
    ) {}

    public function broadcastOn(): array
    {
        return [new PrivateChannel("org.{$this->organizationId}")];
    }

    public function broadcastAs(): string
    {
        return 'notification.created';
    }
}
