<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AdReport extends Model
{
    protected $fillable = [
        'ad_id',
        'reporter_id',
        'reason',
        'description',
        'status',
        'admin_notes',
        'action_taken'
    ];

    protected $dispatchesEvents = [
        'created' => \App\Events\ReportCreated::class,
    ];

    protected $appends = ['risk_score', 'risk_label'];

    public function ad()
    {
        return $this->belongsTo(Ad::class);
    }

    public function reporter()
    {
        return $this->belongsTo(User::class, 'reporter_id');
    }

    /**
     * Calculate risk score based on keywords and reporter stats.
     */
    public function getRiskScoreAttribute()
    {
        $score = 0;
        
        // Critical reasons
        if ($this->reason === 'scam' || $this->reason === 'fraud') $score += 50;
        if ($this->reason === 'prohibited') $score += 30;
        
        // Anonymous reports might be less reliable, or more (context dependent), 
        // strictly following previous logic: guest = +10 risk? 
        // The previous blade logic was: if ($report->reporter_id === null) $riskScore += 10;
        if ($this->reporter_id === null) $score += 10;

        // Keyword analysis
        $keywords = ['bank', 'money', 'transfer', 'western', 'paytm', 'bca', 'crypto', 'telegram', 'whatsapp'];
        foreach ($keywords as $keyword) {
            if (str_contains(strtolower($this->description ?? ''), $keyword)) {
                $score += 30;
                break; // Cap singular keyword match
            }
        }
        
        return min($score, 100);
    }

    /**
     * Get human readable risk label.
     */
    public function getRiskLabelAttribute()
    {
        $score = $this->risk_score;
        if ($score >= 60) return 'High';
        if ($score >= 30) return 'Medium';
        return 'Low';
    }

    /**
     * Scope for filtering by risk.
     */
    public function scopeRiskLevel($query, $level)
    {
        // This is a bit complex since risk is calculated. 
        // Ideally risk should be stored in DB if we want efficient querying.
        // For now, we will process it in memory or simple scopes if possible.
        // Since we are paginating, we can't easily scope by a calculated attribute without raw SQL.
        // We will skip strict database scoping for risk on this iteration and handle it in the controller/view 
        // OR rely on the limited pagination size. 
        // For professional grade, let's keep it simple for now as we don't have a risk_score column.
        return $query; 
    }
}
