<?php
// app/Jobs/SendCampaignNotifications.php
namespace App\Jobs;

use App\Models\Campaign;
use App\Models\Donateur;
use App\Services\LinkGeneratorService;
use App\Jobs\SendLinkNotifications;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendCampaignNotifications implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $campaign;
    protected $donateurIds;
    protected $groupIds;

    /**
     * Create a new job instance.
     *
     * @param Campaign $campaign
     * @param array    $donateurIds
     * @param array    $groupIds
     */
    public function __construct(Campaign $campaign, array $donateurIds = [], array $groupIds = [])
    {
        $this->campaign    = $campaign;
        $this->donateurIds = $donateurIds;
        $this->groupIds    = $groupIds;
    }

    /**
     * Execute the job.
     */
    public function handle(LinkGeneratorService $linkGen)
    {
        // Collecter les donateurs ciblés
        $donateurs = Donateur::query()
            ->when($this->donateurIds, fn($q) => $q->whereIn('id', $this->donateurIds))
            ->when($this->groupIds, fn($q) => $q->orWhereHas('groups', fn($q2) => $q2->whereIn('groups.id', $this->groupIds)))
            ->get();

        foreach ($donateurs as $donateur) {
            // Génération de lien
            $link = $linkGen->generate($this->campaign, $donateur);

            SendLinkNotifications::dispatch($link);
        }
    }
}
