<?php

declare(strict_types=1);

namespace Kylin\RiskEngine\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;

/**
 * 风险事件模型
 *
 * @property int $id
 * @property int $tenant_id
 * @property int $user_id
 * @property string $type
 * @property int $score
 * @property string|null $device_id
 * @property string|null $fingerprint
 * @property string|null $ip
 * @property string|null $geo
 * @property array|null $payload
 * @property int $handled
 * @property \Carbon\Carbon $created_at
 */
final class RiskEvent extends Model
{
    protected $table = 'kr_risk_events';

    protected $guarded = [];

    protected $casts = [
        'payload' => 'array',
        'handled' => 'boolean',
    ];

    public $timestamps = false;

    public static function boot(): void
    {
        parent::boot();
        static::creating(function (self $model) {
            $model->created_at = $model->created_at ?? now();
        });
    }

    /**
     * 未处理的事件
     */
    public function scopeUnhandled($query)
    {
        return $query->where('handled', false);
    }

    /**
     * 按租户筛选
     */
    public function scopeForTenant($query, int $tenantId)
    {
        return $query->where('tenant_id', $tenantId);
    }
}
