<?php

namespace App\Listeners;

use App\Events\DocumentVersionUpdated;
use App\Models\User;
use App\Notifications\DocumentUpdatedNotification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class SendDocumentVersionNotification
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(DocumentVersionUpdated $event): void
    {
        // Notificar a usuarios relevantes
        $users = User::whereHas('roles', function($query) {
            $query->whereIn('name', ['admin', 'approver']);
        })
        ->orWhereHas('projects', function($query) use ($event) {
            $query->where('id', $event->document->project_id);
        })
        ->get();

        foreach ($users as $user) {
            $user->notify(new DocumentUpdatedNotification($event->document));
        }
    }
}
