<?php

namespace App\Jobs;

use App\Models\AiTask;
use App\Models\Campaign;
use App\Models\CampaignMilestone;
use App\Models\CampaignBudgetAllocation;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    protected $aiTask;

    /**
     * Create a new job instance.
     *
     * @param  \App\Models\AiTask  $aiTask
     * @return void
     */
    public function __construct(AiTask $aiTask)
    {
        $this->aiTask = $aiTask;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(): void
    {
        // Get the campaign from the AI task payload
        $payload = $this->aiTask->result_meta;
        $campaignId = $payload['campaign_id'] ?? null;
        
        if (!$campaignId) {
            $this->aiTask->update([
                'status' => 'failed',
                'error_message' => 'Invalid campaign ID in payload',
            ]);
            return;
        }
        
        $campaign = Campaign::find($campaignId);
        if (!$campaign) {
            $this->aiTask->update([
                'status' => 'failed',
                'error_message' => 'Campaign not found',
            ]);
            return;
        }
        
        // Process the AI suggestions based on the task type
        if ($this->aiTask->type === 'campaign_planning') {
            // Brand campaign planning
            // Create milestones from AI response
            $milestones = $payload['milestones'] ?? [];
            foreach ($milestones as $milestoneData) {
                $milestoneData['campaign_id'] = $campaign->id;
                // Convert date string to Carbon instance
                if (isset($milestoneData['due_date'])) {
                    $milestoneData['due_date'] = \Carbon\Carbon::parse($milestoneData['due_date']);
                }
                CampaignMilestone::create($milestoneData);
            }
            
            // Create budget allocations from AI response
            $budgetAllocations = $payload['budget_allocations'] ?? [];
            foreach ($budgetAllocations as $allocationData) {
                $allocationData['campaign_id'] = $campaign->id;
                CampaignBudgetAllocation::create($allocationData);
            }
        } elseif ($this->aiTask->type === 'creator_campaign_planning') {
            // Creator campaign planning
            // Create milestones from AI response
            $milestones = $payload['milestones'] ?? [];
            foreach ($milestones as $milestoneData) {
                $milestoneData['campaign_id'] = $campaign->id;
                // Convert date string to Carbon instance
                if (isset($milestoneData['due_date'])) {
                    $milestoneData['due_date'] = \Carbon\Carbon::parse($milestoneData['due_date']);
                }
                // For creator campaigns, assign milestones to the creator
                $milestoneData['assigned_creator_id'] = $payload['creator_id'] ?? null;
                CampaignMilestone::create($milestoneData);
            }
            
            // Add posting schedule suggestions as milestones
            $postingSchedule = $payload['posting_schedule'] ?? [];
            foreach ($postingSchedule as $scheduleItem) {
                $milestoneData = [
                    'campaign_id' => $campaign->id,
                    'name' => "Post: {$scheduleItem['content_type']} on {$scheduleItem['platform']}",
                    'description' => "Theme: {$scheduleItem['theme']}",
                    'due_date' => \Carbon\Carbon::parse($scheduleItem['date']),
                    'status' => 'pending',
                    'assigned_creator_id' => $payload['creator_id'] ?? null,
                ];
                CampaignMilestone::create($milestoneData);
            }
        }
        
        // Update the AI task status
        $this->aiTask->update([
            'status' => 'completed',
            'result_text' => 'Campaign planning suggestions generated successfully',
        ]);
    }
}
