<?php

namespace App\Listeners;

use App\Events\MessageSent;
use App\Services\AiGuardianService;
use App\Models\User;
use App\Models\Ad;
use App\Models\Notification;
use App\Models\Setting;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class ScanChatMessage implements ShouldQueue
{
    use InteractsWithQueue;

    protected $guardian;

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

    public function handle(MessageSent $event)
    {
        $message = $event->message;
        
        // Scan content
        $result = $this->guardian->scanMessage($message->message);

        // Update Message with Scan Results
        if ($result['detected']) {
            $message->update([
                'is_flagged' => true,
                'flag_reason' => $result['trigger'] . ' (Severity: ' . ($result['severity'] ?? 'HIGH') . ')',
                'risk_score' => ($result['severity'] == 'HIGH') ? 100 : 50
            ]);

            $user = User::find($message->sender_id);
            
            // 1. Flag User Risk Score
            if ($user) {
                $user->increment('risk_score', 20);
            }
            
            // 2. Suspend Active Ads if High Risk
            if (($result['severity'] ?? 'LOW') === 'HIGH') {
                 $activeAds = Ad::where('user_id', $message->sender_id)->where('status', 'Active')->get();
                 foreach ($activeAds as $ad) {
                     $ad->update(['status' => 'Pending']);
                 }
            }

            // 3. Notify Sender (Warning)
            Notification::create([
                'user_id' => $message->sender_id,
                'type' => 'safety_warning',
                'title' => 'Safety Warning',
                'message' => 'Your message was flagged for potential safety violations (' . $result['trigger'] . '). Please review our guidelines.',
                'data' => ['trigger' => $result['trigger']]
            ]);
        }
    }
}
