<?php

namespace App\Models;

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

class WordlingPlay extends Model
{
    protected $fillable = [
        'user_id',
        'wordling_word_id',
        'try_count',
        'is_correct',
        'max_attempts',
        'completed_at',
        'user_submissions',
    ];

    protected $casts = [
        'user_submissions' => 'array',
        'is_correct' => 'boolean',
        'try_count' => 'integer',
        'max_attempts' => 'integer',
        'completed_at' => 'datetime',
    ];

    /**
     * Relationship with WordlingWord
     */
    public function wordlingWord(): BelongsTo
    {
        return $this->belongsTo(WordlingWord::class, 'wordling_word_id');
    }

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

    /**
     * Check if user has completed this game
     */
    public function isCompleted(): bool
    {
        return $this->is_correct || $this->try_count >= $this->wordlingWord->max_attempts;
    }

    /**
     * Get the remaining attempts for the game
     */
    public function getRemainingAttemptsAttribute(): int
    {
        return max(0, $this->wordlingWord->max_attempts - $this->try_count);
    }
}