<?php

namespace Kylin\WordFilter\Models;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Kylin\Core\Models\BaseModel;
use Kylin\WordFilter\Enums\Severity;
use Kylin\WordFilter\Enums\WordStatus;

/**
 * 敏感词模型
 *
 * 存储敏感词及其变体，支持：
 *  - 分类关联（WordCategory）
 *  - 严重等级（Severity）
 *  - 变体检测（is_variant / parent_id）
 *  - 启用/禁用状态
 *
 * @property int       $id
 * @property string    $word           敏感词
 * @property int       $category_id    分类 ID
 * @property Severity  $severity       严重等级
 * @property bool      $is_variant     是否为变体
 * @property int|null  $parent_id      父词 ID（变体指向原始词）
 * @property WordStatus $status        状态
 */
class SensitiveWord extends BaseModel
{
    protected $table = 'kylin_sensitive_words';

    protected $fillable = [
        'word',
        'category_id',
        'severity',
        'is_variant',
        'parent_id',
        'status',
    ];

    protected $casts = [
        'severity' => Severity::class,
        'is_variant' => 'boolean',
        'status' => WordStatus::class,
    ];

    /**
     * 所属分类
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(WordCategory::class, 'category_id');
    }

    /**
     * 父级敏感词（变体词的原始词）
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(self::class, 'parent_id');
    }

    /**
     * 变体词列表
     */
    public function variants(): HasMany
    {
        return $this->hasMany(self::class, 'parent_id');
    }

    /**
     * 是否为变体词
     */
    public function isVariant(): bool
    {
        return $this->is_variant === true;
    }

    /**
     * 是否启用
     */
    public function isActive(): bool
    {
        return $this->status === WordStatus::Active;
    }

    /**
     * 查询作用域：仅启用的敏感词
     */
    public function scopeActive($query)
    {
        return $query->where('status', WordStatus::Active->value);
    }

    /**
     * 查询作用域：仅非变体词（原始词）
     */
    public function scopePrimary($query)
    {
        return $query->where('is_variant', false);
    }

    /**
     * 查询作用域：按严重程度筛选
     */
    public function scopeBySeverity($query, Severity $severity)
    {
        return $query->where('severity', $severity->value);
    }
}
