<?php

namespace App\Models;

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

class Rating extends Model
{
    use HasFactory;

    protected $fillable = [
        'rate_my_pay_id',
        'user_id',
        'rating',
        'salary',
    ];

    protected $casts = [
        'rating' => 'integer',
        'salary' => 'decimal:2',
    ];

    // Relationships
    public function rateMyPay(): BelongsTo
    {
        return $this->belongsTo(RateMyPay::class);
    }

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

    // Accessors
    public function getFormattedSalaryAttribute(): string
    {
        return $this->salary ? number_format($this->salary) . ' USD' : 'Not provided';
    }

    // Methods
    public function updatePostRatingStats(): void
    {
        $this->update([
            'ratings_count' => $this->ratings()->count(),
            'average_rating' => $this->ratings()->avg('rating') ?: 0,
        ]);
    }
}