<?php

namespace App\Models;

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

class Review extends Model
{
    use HasFactory;

    // ── Fillable ───────────────────────────────────────────────
    protected $fillable = [
        'freelance_match_id',
        'reviewer_user_id',
        'freelance_profile_id',
        'rating',
        'comment',
        'posted_as_nickname',
    ];

    // ── Casts ─────────────────────────────────────────────────
    protected $casts = [
        'rating'             => 'integer',
        'posted_as_nickname' => 'boolean',
    ];

    // ── Helpers ───────────────────────────────────────────────

    public function getAuthorNameAttribute(): string
    {
        if ($this->posted_as_nickname) {
            return $this->reviewer->nickname;
        }
        return $this->reviewer->show_real_name
            ? $this->reviewer->name
            : $this->reviewer->nickname;
    }

    // ── Relationships ─────────────────────────────────────────

    public function match(): BelongsTo
    {
        return $this->belongsTo(FreelanceMatch::class, 'freelance_match_id');
    }

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

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