<?php

namespace App\Jobs;

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

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

    /**
     * Execute the job.
     */
    public function handle()
    {
        try {
            // Log start of dispatching
            Log::info('Starting to dispatch due scheduled reels');
            
            // Find all scheduled reels that are due
            $dueReels = ScheduledReel::where('status', 'scheduled')
                ->where('scheduled_at', '<=', now())
                ->get();
                
            Log::info('Found due scheduled reels', ['count' => $dueReels->count()]);

            foreach ($dueReels as $reel) {
                Log::info('Dispatching scheduled reel for processing', [
                    'scheduled_reel_id' => $reel->id,
                    'owner_id' => $reel->owner_id,
                    'owner_type' => $reel->owner_type,
                    'template' => $reel->template
                ]);
                
                // Dispatch the processing job
                ProcessScheduledReel::dispatch($reel);
                
                // Mark as queued
                $reel->markQueued();
            }

            Log::info('Dispatched ' . $dueReels->count() . ' scheduled reels for processing');
        } catch (\Exception $e) {
            Log::error('Failed to dispatch due scheduled reels: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
        }
    }
}