<?php

namespace App\Models;

use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class Participant extends Model
{
    use BelongsToOwner;

    protected $table = 'meet_participants';

    protected $fillable = [
        'uuid', 'owner_ref', 'session_id', 'user_ref', 'display_name', 'email',
        'role', 'status', 'joined_at', 'left_at', 'device_info', 'ip_address',
        'hand_raised', 'speak_requested', 'speak_granted', 'is_muted', 'is_video_off', 'breakout_room_id',
    ];

    protected function casts(): array
    {
        return [
            'joined_at' => 'datetime',
            'left_at' => 'datetime',
            'hand_raised' => 'boolean',
            'speak_requested' => 'boolean',
            'speak_granted' => 'boolean',
            'is_muted' => 'boolean',
            'is_video_off' => 'boolean',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (Participant $participant) {
            if (empty($participant->uuid)) {
                $participant->uuid = (string) Str::uuid();
            }
        });
    }

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

    public function session(): BelongsTo
    {
        return $this->belongsTo(Session::class, 'session_id');
    }

    public function isHost(): bool
    {
        return in_array($this->role, ['host', 'co_host'], true);
    }

    public function isPanelist(): bool
    {
        return $this->role === 'panelist';
    }

    public function isAttendee(): bool
    {
        return $this->role === 'attendee';
    }

    public function canPublishMedia(): bool
    {
        if ($this->speak_granted) {
            return true;
        }

        return $this->role !== 'attendee';
    }

    public function hasSpeakAccess(): bool
    {
        return $this->speak_granted;
    }

    public function breakoutRoom(): BelongsTo
    {
        return $this->belongsTo(BreakoutRoom::class, 'breakout_room_id');
    }

    public function isJoined(): bool
    {
        return $this->status === 'joined';
    }
}
