<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * @property int      $id
 * @property int      $user_id
 * @property int      $achievement_id
 * @property int|null $progress
 *
 * @property-read User        $user
 * @property-read Achievement $achievement
 */
class UserAchievement extends Model
{
    protected $fillable = [
        'user_id',
        'achievement_id',
        'progress',
    ];

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

    protected $appends = [
        'unlocked',
    ];

    protected function unlocked(): Attribute
    {
        return Attribute::make(
            get: function () {
                if (!$this->achievement) return false;
                if (!$this->achievement->progressive || !$this->achievement->threshold) return true;
                return ($this->progress ?? 0) >= $this->achievement->threshold;
            }
        );
    }

    // ---------------------------------------------------------------
    // Relationships
    // ---------------------------------------------------------------

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

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