<?php

namespace Artemis\Faq\Traits;

use Artemis\Faq\Models\Vote;
use Artemis\Faq\Enums\VoteType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;

/** @mixin Model */
trait Votable
{
    /**
     * Define a polymorphic relationship to the votes table.
     */
    public function votes(): MorphMany
    {
        return $this->morphMany(Vote::class, 'votable');
    }
    
    public function upVote(int $userId): void
    {
        $this->votes()->updateOrCreate([
            'user_id' => $userId
        ], [
            'vote_type' => VoteType::UP
        ]);
    }
    
    public function downVote(int $userId): void
    {
        $this->votes()->updateOrCreate([
            'user_id' => $userId
        ], [
            'vote_type' => VoteType::DOWN
        ]);
    }
    
    public function removeVote(int $userId): void
    {
        $this->votes()
            ->where('user_id', $userId)
            ->delete();
    }
    
    public function isUpVotedBy(int $userId): bool
    {
        return $this->votes()
            ->where('user_id', $userId)
            ->where('vote_type', VoteType::UP)
            ->exists();
    }
    
    public function isDownVotedBy(int $userId): bool
    {
        return $this->votes()
            ->where('user_id', $userId)
            ->where('vote_type', VoteType::DOWN)
            ->exists();
    }
    
    public function upVotesCount(): int
    {
        return $this->votes()
            ->where('vote_type', VoteType::UP)
            ->count();
    }
    
    public function downVotesCount(): int
    {
        return $this->votes()
            ->where('vote_type', VoteType::DOWN)
            ->count();
    }
    
    public function voteScore(): int
    {
        return $this->upvotesCount() - $this->downvotesCount();
    }
}
