<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * @property int                   $id
 * @property string                $name
 * @property string                $internal_name
 * @property string                $short_description
 * @property string                $long_description
 * @property string                $icon
 * @property bool                  $progressive
 * @property string|null           $difficulty_description
 * @property int                   $achievement_category_id
 * @property int                   $achievement_difficulty_id
 *
 * @property-read AchievementCategory    $category
 * @property-read AchievementDifficulty  $difficulty
 * @property-read Collection<int, UserAchievement> $userAchievements
 * @property-read Collection<int, User>  $users
 */
class Achievement extends Model
{
    public $timestamps = false;
    protected $fillable = [
        'name',
        'internal_name',
        'short_description',
        'long_description',
        'icon',
        'progressive',
        'difficulty_description',
        'achievement_category_id',
        'achievement_difficulty_id',
        'threshold',
        'has_page',
        'sort_order',
    ];

    protected $casts = [
        'has_page' => 'boolean',
        'progressive' => 'boolean',
        'threshold' => 'integer',
    ];


    public function getRouteKeyName(): string
    {
        return 'internal_name';
    }

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

    public function category(): BelongsTo
    {
        return $this->belongsTo(AchievementCategory::class, 'achievement_category_id');
    }

    public function difficulty(): BelongsTo
    {
        return $this->belongsTo(AchievementDifficulty::class, 'achievement_difficulty_id');
    }

    public function userAchievements(): HasMany
    {
        return $this->hasMany(UserAchievement::class, 'achievement_id');
    }

    /** Users who have unlocked (or are progressing toward) this achievement. */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'user_achievements')
            ->withPivot('progress')
            ->withTimestamps();
    }
}
