<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class Review extends Model
{
    use HasFactory;

    protected $table = 'p2p_reviews';

    protected $fillable = [
        'trade_id',
        'reviewer_id',
        'reviewed_id',
        'rating',
        'comment',
    ];

    protected $casts = [
        'rating' => 'integer',
    ];

    // Relationships
    public function trade()
    {
        return $this->belongsTo(Trade::class);
    }

    public function reviewer()
    {
        return $this->belongsTo(User::class, 'reviewer_id');
    }

    public function reviewed()
    {
        return $this->belongsTo(User::class, 'reviewed_id');
    }

    // Boot method to update user rating when review is created/updated
    protected static function boot()
    {
        parent::boot();

        static::created(function ($review) {
            $review->reviewed->updateRating();
        });

        static::updated(function ($review) {
            $review->reviewed->updateRating();
        });

        static::deleted(function ($review) {
            $review->reviewed->updateRating();
        });
    }
}