<?php

namespace App\Models;

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

class Review extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'property_id',
        'reviewer_id',
        'rating',
        'comment',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'rating' => 'integer',
        ];
    }

    /**
     * Get the property that was reviewed.
     */
    public function property()
    {
        return $this->belongsTo(Property::class);
    }

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

    /**
     * Rating constants
     */
    const RATING_VERY_POOR = 1;
    const RATING_POOR = 2;
    const RATING_AVERAGE = 3;
    const RATING_GOOD = 4;
    const RATING_EXCELLENT = 5;

    /**
     * Get rating options
     */
    public static function getRatingOptions(): array
    {
        return [
            self::RATING_VERY_POOR => 'Very Poor',
            self::RATING_POOR => 'Poor',
            self::RATING_AVERAGE => 'Average',
            self::RATING_GOOD => 'Good',
            self::RATING_EXCELLENT => 'Excellent',
        ];
    }

    /**
     * Scope to filter by property
     */
    public function scopeForProperty($query, int $propertyId)
    {
        return $query->where('property_id', $propertyId);
    }

    /**
     * Scope to filter by reviewer
     */
    public function scopeByReviewer($query, int $reviewerId)
    {
        return $query->where('reviewer_id', $reviewerId);
    }

    /**
     * Scope to filter by rating
     */
    public function scopeWithRating($query, int $rating)
    {
        return $query->where('rating', $rating);
    }

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