<?php

namespace App\Models;

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

class LiveStream extends Model
{
    use BelongsToOwner;

    protected $table = 'meet_live_streams';

    protected $fillable = [
        'uuid', 'owner_ref', 'session_id', 'platform', 'rtmp_url', 'stream_key',
        'status', 'layout', 'health', 'started_at', 'ended_at',
    ];

    protected function casts(): array
    {
        return [
            'started_at' => 'datetime',
            'ended_at' => 'datetime',
        ];
    }

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

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

    public function setStreamKeyAttribute(?string $value): void
    {
        $this->attributes['stream_key'] = $value ? Crypt::encryptString($value) : null;
    }

    public function getStreamKeyAttribute(?string $value): ?string
    {
        if (! $value) {
            return null;
        }

        try {
            return Crypt::decryptString($value);
        } catch (\Throwable) {
            return null;
        }
    }
}
