<?php

namespace App\Listeners;

use App\Events\ReportCreated;
use App\Services\AiGuardianService;
use App\Models\Notification;
use App\Models\Setting;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class MonitorAdActivity implements ShouldQueue
{
    use InteractsWithQueue;

    protected $guardian;

    public function __construct(AiGuardianService $guardian)
    {
        $this->guardian = $guardian;
    }

    public function handle(ReportCreated $event)
    {
        $report = $event->report;
        $ad = $report->ad;

        if (!$ad) return;

        // Check if Guardian is enabled
        $enabled = Setting::where('key', 'guardian_enabled')->value('value');
        if ($enabled != '1') return;

        // Use Guardian Service to evaluate ad health
        $result = $this->guardian->evaluateAdHealth($ad);

        if ($result['action'] === 'SUSPEND') {
            // Suspend the ad
            $ad->update(['status' => 'Pending']);

            // Notify User
            Notification::create([
                'user_id' => $ad->user_id,
                'type' => 'ad_suspended',
                'title' => 'Ad Temporarily Suspended',
                'message' => $result['reason'] ?? 'Your ad needs review.',
                'data' => ['ad_id' => $ad->id]
            ]);

            // Notify Admin (could be a dedicated admin notification channel)
            // ...
        }
    }
}
