<?php

namespace App\Jobs;

use App\Models\SocialComment;
use App\Models\AutoReplySetting;
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 ProcessNewCreatorSocialCommentsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $creatorId;

    /**
     * Create a new job instance.
     *
     * @param int $creatorId
     * @return void
     */
    public function __construct($creatorId)
    {
        $this->creatorId = $creatorId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Get auto-reply settings for the creator
        $settings = AutoReplySetting::where('creator_id', $this->creatorId)->first();
        
        if (!$settings || !$settings->enabled) {
            Log::info("Auto-reply not enabled for creator: " . $this->creatorId);
            return;
        }
        
        // Get unprocessed comments for this creator (comments without auto-reply suggestions)
        $unprocessedComments = SocialComment::where('creator_id', $this->creatorId)
            ->whereDoesntHave('autoReplySuggestions')
            ->orderBy('published_at', 'asc')
            ->limit(50) // Process in batches to avoid memory issues
            ->get();
        
        Log::info("Found " . $unprocessedComments->count() . " unprocessed comments for creator: " . $this->creatorId);
        
        // Process each comment
        foreach ($unprocessedComments as $comment) {
            // Dispatch job to generate auto-reply suggestion
            GenerateAutoReplySuggestionsJob::dispatch($comment->id, null, $this->creatorId);
        }
    }
}