<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use App\Models\Show;
use App\Services\ActivityLogService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Inertia\Inertia;
use Inertia\Response;

class LivePlayerController extends Controller
{
    public function __construct(
        protected ActivityLogService $activityLogService
    ) {}

    /**
     * Display live player dengan validasi keamanan yang ketat
     */
    public function player(Request $request, string $slug): Response|\Illuminate\Http\RedirectResponse
    {
        // Validasi: User harus sudah login (middleware auth sudah handle, tapi double check)
        $user = Auth::user();
        if (! $user) {
            abort(401, 'Anda harus login untuk mengakses live player');
        }

        // Validasi: Session harus valid
        if (! $request->session()->has('_token')) {
            abort(403, 'Session tidak valid');
        }

        // Cari show berdasarkan slug_live
        $show = Show::where('slug_live', $slug)->first();
        if (! $show) {
            abort(404, 'Show tidak ditemukan');
        }

        // Validasi: Check streaming maintenance
        if (Setting::isEnabled('streaming_maintenance', false)) {
            return redirect()->route('dashboard')->with('error', 'Akses streaming sedang dalam mode maintenance. Silakan coba lagi nanti.');
        }

        // Validasi: Show harus sedang live
        if (! $show->is_live) {
            return redirect()->route('dashboard')->with('error', 'Show ini tidak sedang live');
        }

        // Validasi: User harus memiliki akses ke show ini (cek membership atau purchased)
        if (! $user->hasAccessToShow($show)) {
            abort(403, 'Anda tidak memiliki akses ke show ini');
        }

        // Cache key untuk validasi akses (user_id + show_id + session_id)
        $sessionId = $request->session()->getId();
        $cacheKey = "live_access:{$user->id}:{$show->id}:{$sessionId}";

        // Cek cache untuk validasi akses (expiry 1 jam)
        $accessValidated = Cache::get($cacheKey);

        if (! $accessValidated) {
            // Simpan validasi akses di cache dengan expiry 1 jam
            // Cache menyimpan timestamp akses terakhir
            Cache::put($cacheKey, [
                'user_id' => $user->id,
                'show_id' => $show->id,
                'session_id' => $sessionId,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
                'accessed_at' => now()->timestamp,
            ], now()->addHour());
        } else {
            // Update timestamp akses terakhir
            $accessValidated['accessed_at'] = now()->timestamp;
            Cache::put($cacheKey, $accessValidated, now()->addHour());
        }

        // Log activity
        $this->activityLogService->log(
            action: 'access_live_player',
            description: "Akses live player for show: {$show->title}",
            model: $show,
            properties: [
                'show_id' => $show->id,
                'show_title' => $show->title,
                'showId' => $show->showId,
                'slug_live' => $show->slug_live,
            ],
            request: $request
        );

        // Get stream server URL from config
        $streamServerUrl = config('services.stream_server_url', 'https://api.ngidolihub.my.id');

        return Inertia::render('LivePlayer', [
            'show' => $show,
            'streamServerUrl' => $streamServerUrl,
            'slugLive' => $show->slug_live,
        ]);
    }
}
