<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\User;
use App\Notifications\NewDealNotification;
use Illuminate\Support\Facades\Log;

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

    public $deal;
    public $tries = 3; // Retry 3 times if fails
    public $timeout = 300; // 5 minutes timeout

    /**
     * Create a new job instance.
     */
    public function __construct($deal)
    {
        $this->deal = $deal;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
{
    try {
        Log::info('Starting bulk deal notification for: ' . $this->deal->title);
        
        // Get all non-admin users (customers)
        $users = User::where('role', '!=', 'admin')
                    ->whereNotNull('email_verified_at') // Only verified users
                    ->chunk(100, function ($users) {
                        foreach ($users as $user) {
                            try {
                                $user->notify(new NewDealNotification($this->deal));
                                Log::info('Sent deal notification to: ' . $user->email);
                            } catch (\Exception $e) {
                                Log::error('Failed to send to ' . $user->email . ': ' . $e->getMessage());
                                continue;
                            }
                        }
                    });
        
        Log::info('Completed bulk deal notification for: ' . $this->deal->title);
        
    } catch (\Exception $e) {
        Log::error('Job failed: ' . $e->getMessage());
        throw $e; // This will trigger retry
    }

    }

    /**
     * Handle a job failure.
     */
    public function failed(\Throwable $exception): void
    {
        Log::error('SendDealNotificationToAllUsers job failed: ' . $exception->getMessage());
    }
}