<?php

namespace App\Jobs;

use App\Models\User;
use App\Services\NotificationChannelService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendBroadcastChannelsJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * @param  array<int, string>  $channels
     */
    public function __construct(
        private readonly string $role,
        private readonly string $title,
        private readonly string $message,
        private readonly ?string $link,
        private readonly array $channels
    ) {
    }

    public function handle(NotificationChannelService $channelService): void
    {
        User::query()
            ->select([
                'id',
                'name',
                'email',
                'mobile',
                'notify_sms_enabled',
                'notify_email_enabled',
                'notify_whatsapp_enabled',
            ])
            ->where('role', $this->role)
            ->orderBy('id')
            ->chunkById(200, function ($users) use ($channelService): void {
                foreach ($users as $user) {
                    $channelService->sendToUserChannels(
                        $user,
                        $this->title,
                        $this->message,
                        $this->link,
                        $this->channels
                    );
                }
            });
    }
}

