<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class WatchParty extends Model
{
    protected $fillable = [
        'room_code', 'host_user_id', 'episode_id',
        'current_sec', 'is_playing', 'synced_at',
        'max_members', 'is_private', 'password',
    ];

    protected $casts = [
        'is_playing' => 'boolean',
        'is_private' => 'boolean',
        'current_sec'=> 'integer',
        'synced_at'  => 'datetime',
    ];

    public function host()    { return $this->belongsTo(User::class, 'host_user_id'); }
    public function episode() { return $this->belongsTo(Episode::class); }
    public function members() { return $this->hasMany(WatchPartyMember::class, 'party_id'); }

    public function activeMembers()
    {
        return $this->members()->where('last_ping', '>=', now()->subSeconds(30));
    }

    public static function generateCode(): string
    {
        do {
            $code = strtoupper(Str::random(6));
        } while (self::where('room_code', $code)->exists());

        return $code;
    }
}
