<?php

namespace App\Models;

use App\Enums\GameEnum;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class HexlingWord extends Model
{
    use HasFactory;

    protected $fillable = [
        'game_id',
        'root_word',
        'center_letter',
        'secret_words',
        'total_levels',
        'total_points',
        'game_date',
        'status',
    ];

    protected $casts = [
        'secret_words' => 'array',
        'game_date' => 'date',
        'status' => GameEnum::class,
    ];

    public function getSearchAttribute()
    {
        return [
            'root_word',
            'center_letter',
            'secret_words',
            'total_levels',
            'total_points',
            'game_date',
            'status',
        ];
    }

    // Many-to-many with badges - FIXED RELATIONSHIP
    public function badges()
    {
        return $this->belongsToMany(
            HexlingBadge::class,
            'hexling_badge_hexling_word',
            'hexling_words_id',
            'hexling_badges_id'
        );
    }

    // One-to-many with players
    public function players()
    {
        return $this->hasMany(HexlingPlay::class, 'hexling_word_id');
    }

    /**
     * Check if the game is active based on status
     */
    public function isActive(): bool
    {
        return $this->status === GameEnum::ACTIVE;
    }

    /**
     * Get active players count
     */
    public function getActivePlayersCountAttribute(): int
    {
        return $this->players()->count();
    }

    /**
     * Get completion rate percentage
     */
    public function getCompletionRateAttribute(): float
    {
        $totalPlayers = $this->active_players_count;
        if ($totalPlayers === 0) {
            return 0;
        }

        $completedPlayers = $this->players()->whereNotNull('completed_at')->count();

        return round(($completedPlayers / $totalPlayers) * 100, 2);
    }
}