<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class RiskAssessment extends Model
{
    use HasFactory;

    protected $fillable = [
        'customer_email',
        'transaction_type',
        'amount',
        'risk_score',
        'risk_level',
        'payment_allowed',
        'requires_3ds',
        'max_amount_allowed',
        'risk_factors',
        'recommended_actions',
        'card_brand',
        'card_country',
        'ip_address',
        'attempt_type',
        'currency',
        'card_fingerprint',
        'subscription_id',
        'fraud_warning'
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'risk_score' => 'integer',
        'payment_allowed' => 'boolean',
        'requires_3ds' => 'boolean',
        'max_amount_allowed' => 'decimal:2',
        'risk_factors' => 'array',
        'recommended_actions' => 'array'
    ];

    /**
     * Get the customer associated with this risk assessment
     */
    public function customer()
    {
        return $this->belongsTo(User::class, 'customer_email', 'email');
    }

    /**
     * Scope for high-risk assessments
     */
    public function scopeHighRisk($query)
    {
        return $query->whereIn('risk_level', ['high', 'very_high']);
    }

    /**
     * Scope for recent assessments
     */
    public function scopeRecent($query, $days = 30)
    {
        return $query->where('created_at', '>=', now()->subDays($days));
    }

    /**
     * Get risk level color for UI display
     */
    public function getRiskLevelColorAttribute()
    {
        return [
            'low' => 'success',
            'medium' => 'warning',
            'high' => 'danger',
            'very_high' => 'dark'
        ][$this->risk_level] ?? 'secondary';
    }

    /**
     * Get formatted risk score
     */
    public function getFormattedRiskScoreAttribute()
    {
        return $this->risk_score . '/100';
    }

    /**
     * Check if customer requires manual review
     */
    public function getRequiresManualReviewAttribute()
    {
        return in_array($this->risk_level, ['high', 'very_high']) || 
               !$this->payment_allowed;
    }
} 