<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Review extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'reviewer_id',
        'reviewee_id',
        'ad_id',
        'rating',
        'review_text',
        'ad_title',
        'ad_category',
        'transaction_type',
        'is_verified_purchase',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'is_verified_purchase' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    /**
     * Get the user who wrote this review.
     */
    public function reviewer()
    {
        return $this->belongsTo(User::class, 'reviewer_id');
    }

    /**
     * Get the user being reviewed.
     */
    public function reviewee()
    {
        return $this->belongsTo(User::class, 'reviewee_id');
    }

    /**
     * Get the ad associated with this review (nullable if ad deleted).
     */
    public function ad()
    {
        return $this->belongsTo(Ad::class);
    }

    /**
     * Scope a query to only include reviews with a specific rating.
     */
    public function scopeRated($query, int $rating)
    {
        return $query->where('rating', $rating);
    }

    /**
     * Scope a query to only include recent reviews.
     */
    public function scopeRecent($query, int $limit = 10)
    {
        return $query->orderBy('created_at', 'desc')->limit($limit);
    }

    /**
     * Scope a query to only include verified purchase reviews.
     */
    public function scopeVerified($query)
    {
        return $query->where('is_verified_purchase', true);
    }

    /**
     * Scope a query to only include reviews with text comments.
     */
    public function scopeWithComment($query)
    {
        return $query->whereNotNull('review_text')->where('review_text', '!=', '');
    }

    /**
     * Get the time ago formatted string.
     */
    public function getTimeAgoAttribute()
    {
        return $this->created_at->diffForHumans();
    }

    /**
     * Check if the review has ad information.
     */
    public function getHasAdInfoAttribute()
    {
        return !empty($this->ad_title) || !empty($this->ad_category);
    }
}
