<?php

namespace App\Services\Meet;

use App\Models\LiveStream;
use App\Models\Session;
use App\Models\User;
use Illuminate\Support\Str;

class LiveStreamService
{
    /** @var array<string, string> */
    public const PLATFORMS = [
        'youtube' => 'YouTube',
        'facebook' => 'Facebook Live',
        'linkedin' => 'LinkedIn Live',
        'custom' => 'Custom RTMP',
    ];

    /** @var array<string, string> */
    public const LAYOUTS = [
        'speaker' => 'Speaker view',
        'gallery' => 'Gallery view',
        'screen' => 'Screen share focus',
    ];

    /**
     * @param  array<string, mixed>  $data
     */
    public function configure(Session $session, User $host, array $data): LiveStream
    {
        $platform = $data['platform'] ?? 'custom';
        $rtmpUrl = $this->defaultRtmpUrl($platform, $data['rtmp_url'] ?? null);

        return LiveStream::updateOrCreate(
            ['session_id' => $session->id, 'platform' => $platform],
            [
                'owner_ref' => $session->owner_ref,
                'rtmp_url' => $rtmpUrl,
                'stream_key' => $data['stream_key'] ?? '',
                'layout' => $data['layout'] ?? 'speaker',
                'status' => 'idle',
            ],
        );
    }

    public function start(LiveStream $stream): LiveStream
    {
        $stream->update([
            'status' => 'live',
            'started_at' => now(),
            'ended_at' => null,
            'health' => 'ok',
        ]);

        AuditLogger::record(
            $stream->owner_ref,
            'livestream.started',
            $stream->session->room->organization_id,
            $stream->owner_ref,
            LiveStream::class,
            $stream->id,
        );

        return $stream->fresh();
    }

    public function stop(LiveStream $stream): LiveStream
    {
        $stream->update([
            'status' => 'stopped',
            'ended_at' => now(),
        ]);

        return $stream->fresh();
    }

    protected function defaultRtmpUrl(string $platform, ?string $custom): string
    {
        if ($custom) {
            return $custom;
        }

        return match ($platform) {
            'youtube' => 'rtmp://a.rtmp.youtube.com/live2',
            'facebook' => 'rtmps://live-api-s.facebook.com:443/rtmp/',
            'linkedin' => 'rtmp://stream.linkedin.com:1935/live/',
            default => '',
        };
    }
}
