<?php

namespace App\Jobs;

use App\Models\AiJob;
use App\Models\ContentIdea;
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;
use Illuminate\Support\Facades\Auth;

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

    protected $aiJobId;
    protected $payload;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $aiJob = AiJob::find($this->aiJobId);
        
        if (!$aiJob) {
            Log::error("AI Job not found: " . $this->aiJobId);
            return;
        }
        
        // Update status to generating
        $aiJob->update(['status' => 'generating']);
        
        try {
            // Simulate AI processing delay
            sleep(3);
            
            // Generate content ideas based on payload
            $contentIdeas = $this->generateContentIdeas($this->payload);
            
            // Save content ideas to database
            foreach ($contentIdeas as $ideaData) {
                ContentIdea::create([
                    'creator_id' => $aiJob->creator_id,
                    'brand_id' => null, // Not associated with a brand
                    'campaign_id' => null, // Not associated with a campaign
                    'user_id' => Auth::id(), // For audit trail
                    'caption' => $ideaData['caption'],
                    'hashtags' => $ideaData['hashtags'],
                    'creative_hints' => $ideaData['creative_hints'],
                    'status' => 'draft',
                ]);
            }
            
            // Update AI job with results
            $aiJob->update([
                'status' => 'ready',
                'result_text' => 'Generated ' . count($contentIdeas) . ' content ideas',
                'result_meta' => ['content_ideas_count' => count($contentIdeas)],
                'provider' => 'openai-gpt-4',
                'token_usage' => count($contentIdeas) * 100, // Rough estimation
                'completed_at' => now(),
            ]);
            
            // Log token usage for cost tracking
            Log::info("Content ideas generated for job: " . $aiJob->job_id . " with token usage: " . (count($contentIdeas) * 100));
        } catch (\Exception $e) {
            // Update AI job with error
            $aiJob->update([
                'status' => 'failed',
                'error_message' => $e->getMessage(),
            ]);
            
            Log::error("Content ideas generation failed for job: " . $aiJob->job_id . " with error: " . $e->getMessage());
        }
    }
    
    /**
     * Generate content ideas based on payload.
     *
     * @param array $payload
     * @return array
     */
    protected function generateContentIdeas($payload)
    {
        // In a real implementation, this would call an AI service
        // For now, we'll generate mock content ideas
        
        $ideas = [];
        $numberOfIdeas = $payload['number_of_ideas'] ?? 5;
        
        // Get creator's social accounts to tailor ideas
        $platform = $payload['platform'] ?? 'social media';
        $style = $payload['style'] ?? 'casual';
        $niche = $payload['topic'] ?? 'general';
        
        for ($i = 1; $i <= $numberOfIdeas; $i++) {
            $ideas[] = [
                'caption' => "Creative content idea #{$i} about {$niche} for {$platform} in a {$style} style",
                'hashtags' => [
                    "#{$platform}",
                    "#{$niche}",
                    "#contentcreator",
                    "#{$style}"
                ],
                'creative_hints' => "Consider using {$style} tone and focus on {$niche} for this idea. Perfect for {$platform} audience.",
            ];
        }
        
        return $ideas;
    }
}