<?php

declare(strict_types=1);

namespace App\Models;

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

final class BlogPostReview extends Model
{
    /** @use HasFactory<\Database\Factories\BlogPostReviewFactory> */
    use HasFactory;

    protected $fillable = [
        'blog_post_id',
        'user_id',
        'guest_name',
        'guest_email',
        'rating',
        'body',
        'is_approved',
    ];

    protected function casts(): array
    {
        return [
            'blog_post_id' => 'integer',
            'user_id' => 'integer',
            'rating' => 'integer',
            'is_approved' => 'boolean',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
        ];
    }

    /**
     * @param  Builder<BlogPostReview>  $query
     * @return Builder<BlogPostReview>
     */
    public function scopeApproved(Builder $query): Builder
    {
        return $query->where('is_approved', true);
    }

    /**
     * @param  Builder<BlogPostReview>  $query
     * @return Builder<BlogPostReview>
     */
    public function scopePendingApproval(Builder $query): Builder
    {
        return $query->where('is_approved', false);
    }

    public function reviewerDisplayName(): string
    {
        if ($this->user_id !== null) {
            return $this->user?->name ?? 'Reader';
        }

        return $this->guest_name ?? 'Reader';
    }

    /**
     * @return BelongsTo<BlogPost, $this>
     */
    public function post(): BelongsTo
    {
        return $this->belongsTo(BlogPost::class, 'blog_post_id');
    }

    /**
     * @return BelongsTo<User, $this>
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}
