<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ForumPost extends Model
{
    use HasFactory;

    protected $fillable = [
        'thread_id',
        'user_id',
        'parent_id',
        'content',
        'votes_count',
    ];

    /**
     * Get the thread that owns the post.
     */
    public function thread(): BelongsTo
    {
        return $this->belongsTo(ForumThread::class, 'thread_id');
    }

    /**
     * Get the user that created the post.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the parent post (if this is a reply).
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(ForumPost::class, 'parent_id');
    }

    /**
     * Get the replies to this post.
     */
    public function replies(): HasMany
    {
        return $this->hasMany(ForumPost::class, 'parent_id');
    }

    /**
     * Get the votes for this post.
     */
    public function votes(): HasMany
    {
        return $this->hasMany(ForumVote::class, 'post_id');
    }

    /**
     * Get user's vote on this post.
     */
    public function userVote(?int $userId = null): ?ForumVote
    {
        $userId = $userId ?? auth()->id();

        if (! $userId) {
            return null;
        }

        return $this->votes()->where('user_id', $userId)->first();
    }

    /**
     * Calculate and update votes count cache.
     */
    public function updateVotesCount(): void
    {
        $upVotes = $this->votes()->where('vote_type', 'up')->count();
        $downVotes = $this->votes()->where('vote_type', 'down')->count();

        $this->update(['votes_count' => $upVotes - $downVotes]);
    }

    /**
     * Get replies count.
     */
    public function getRepliesCountAttribute(): int
    {
        return $this->replies()->count();
    }
}
