<?php

namespace App\Models;

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 $fillable = [
        'topic_id',
        'user_id',
        'content',
        'likes',
        'dislikes',
        'reply_to_id',
        'edited_at',
        'edited_by',
    ];

    protected $casts = [
        'likes' => 'integer',
        'dislikes' => 'integer',
        'edited_at' => 'datetime',
    ];

    public function topic(): BelongsTo
    {
        return $this->belongsTo(ForumTopic::class, 'topic_id');
    }

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

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

    public function replyTo(): BelongsTo
    {
        return $this->belongsTo(__CLASS__, 'reply_to_id');
    }

    public function replies(): HasMany
    {
        return $this->hasMany(__CLASS__, 'reply_to_id');
    }

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

    public function isEdited(): bool
    {
        return !is_null($this->edited_at);
    }

    public function isLikedBy(int $userId): bool
    {
        return $this->forumLikes()
            ->where('user_id', $userId)
            ->where('type', 'like')
            ->exists();
    }

    public function isDislikedBy(int $userId): bool
    {
        return $this->forumLikes()
            ->where('user_id', $userId)
            ->where('type', 'dislike')
            ->exists();
    }

    public function getUserLikeType(int $userId): ?string
    {
        $like = $this->forumLikes()
            ->where('user_id', $userId)
            ->first();

        return $like?->type;
    }
}
