<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class PostBookmark extends Model
{
    protected $table = 'tb_post_bookmark';
    protected $primaryKey = 'id';

    public $keyType = 'int';
    public $incrementing = true;
    public $timestamps = true;

    const CREATED_AT = 'created_at';
    const UPDATED_AT = null;

    protected $guarded = [];

    public function board()
    {
        return $this->belongsTo(Board::class)->withDefault();
    }

    public function post()
    {
        return $this->belongsTo(Post::class)->withDefault();
    }

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

    /**
     * 게시글 즐겨찾기 등록
     */
    public function register(array $params): int
    {
        return $this->insertGetId($params);
    }

    /**
     * 게시글 즐겨찾기 삭제
     */
    public function remove(Post $post, int $userID): bool
    {
        return $this->where([
            ['board_id', $post->board_id],
            ['post_id', $post->id],
            ['user_id', $userID]
        ])->delete();
    }

    /**
     * 게시글 즐겨찾기 되어있는지 확인
     */
    public function isAlready(Post $post, ?int $userID): bool
    {
        return $this->where([
            ['board_id', $post->board_id],
            ['post_id', $post->id],
            ['user_id', $userID]
        ])->exists();
    }

    /**
     * 게시글 등록된 즐겨찾기 수
     */
    public function rows(Post $post): int
    {
        return $this->where([
            ['board_id', $post->board_id],
            ['post_id', $post->id]
        ])->count();
    }
}
