<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class ForumPost extends Model
{
    use SoftDeletes;

    protected $table = 'forum_posts';

    protected $fillable = [
        'id',
        'thread_id',
        'topic_id',
        'source_ip_hash',
        'user_id',
        'content',
        'content_hash',
        'is_edited',
        'edited_at',
        'spam_score',
        'quality_score',
        'ai_spam_score',
        'ai_toxicity_score',
        'behavior_score',
        'link_score',
        'learning_score',
        'risk_score',
        'trust_modifier',
        'flagged',
        'flagged_reason',
        'moderation_checked',
        'moderation_status',
        'moderation_labels',
        'moderation_meta',
        'last_ai_scan_at',
    ];

    public $incrementing = true;

    protected $casts = [
        'is_edited' => 'boolean',
        'edited_at' => 'datetime',
        'spam_score' => 'integer',
        'quality_score' => 'integer',
        'ai_spam_score' => 'integer',
        'ai_toxicity_score' => 'integer',
        'behavior_score' => 'integer',
        'link_score' => 'integer',
        'learning_score' => 'integer',
        'risk_score' => 'integer',
        'trust_modifier' => 'integer',
        'flagged' => 'boolean',
        'moderation_checked' => 'boolean',
        'moderation_labels' => 'array',
        'moderation_meta' => 'array',
        'last_ai_scan_at' => 'datetime',
    ];

    public function thread(): BelongsTo
    {
        return $this->belongsTo(ForumThread::class, 'thread_id');
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function attachments(): HasMany
    {
        return $this->hasMany(ForumAttachment::class, 'post_id');
    }

    public function scopeInThread(Builder $query, int $threadId): Builder
    {
        return $query->where('thread_id', $threadId);
    }

    public function scopeVisible(Builder $query): Builder
    {
        return $query;
    }

    public function scopePinned(Builder $query): Builder
    {
        return $query->whereHas('thread', fn (Builder $threadQuery) => $threadQuery->where('is_pinned', true));
    }

    public function scopeRecent(Builder $query): Builder
    {
        return $query->orderByDesc('created_at')->orderByDesc('id');
    }
}
