<?php

namespace App\Models;

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

class HexlingPlay extends Model
{
    use HasFactory;

    protected $fillable = [
        'hexling_word_id',
        'user_id',
        'player_game_level',
        'earned_points',
        'user_submissions',
        'earned_badge_ids',
        'completed_at',
    ];

    protected $casts = [
        'user_submissions' => 'array',
        'earned_badge_ids' => 'array',
        'completed_at' => 'datetime',
    ];

    public function word()
    {
        return $this->belongsTo(HexlingWord::class, 'hexling_word_id');
    }

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

    /**
     * Check if user has completed this game
     */
    public function isCompleted(): bool
    {
        return !is_null($this->completed_at);
    }

    /**
     * Accessor to get full badge data from IDs
     */
    public function getEarnedBadgesAttribute()
    {
        if (empty($this->earned_badge_ids)) {
            return collect();
        }

        return HexlingBadge::whereIn('id', $this->earned_badge_ids)
            ->orderBy('badge_order')
            ->get();
    }
}