<?php

namespace App\Jobs;

use App\Models\AdCampaign;
use App\Services\MetaAdsService;
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 SyncMetaCampaignInsightsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $campaign;

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

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        try {
            if (! $this->campaign->meta_campaign_id) {
                Log::info("SyncMetaCampaignInsightsJob: Skipping campaign {$this->campaign->id} (No Meta ID)");

                return;
            }

            $integration = $this->campaign->facebookIntegration;
            if (! $integration || ! $integration->access_token) {
                Log::error("SyncMetaCampaignInsightsJob: No integration found for campaign {$this->campaign->id}");

                return;
            }

            $service = new MetaAdsService($integration);
            $service->syncCampaignInsights($this->campaign);

            Log::info("SyncMetaCampaignInsightsJob: Successfully synced campaign {$this->campaign->id}");

        } catch (\Exception $e) {
            Log::error("SyncMetaCampaignInsightsJob: Failed to sync campaign {$this->campaign->id}. Error: ".$e->getMessage());
            // Don't fail the job hard so other jobs can continue if batch processed,
            // but for single job it's fine.
        }
    }
}
