<?php

namespace App\Http\Controllers;

use App\Models\Alert;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class MediaStreamController extends Controller
{
    /**
     * Resolves localized temporary cryptographic signatures access links for media playback pipelines.
     */
    public function getAuthenticatedStreamUrl(Request $request, $alertId)
    {
        // Enforce user authorization layer checks (Only active security responders/admins read video logs)
        if (!in_array($request->user()->role, ['admin', 'agency'])) {
            return response()->json(['error' => 'Access Denied. Insufficient clearance credentials.'], 403);
        }

        $alert = Alert::findOrFail($alertId);

        if (!$alert->video_path || !Storage::disk('public')->exists($alert->video_path)) {
            return response()->json(['error' => 'Target multimedia recording block does not exist on disk layers.'], 404);
        }

        // Generate temporary encrypted file download links expiring precisely after 30 minutes duration intervals
        $secureUrl = URL::temporarySignedRoute(
            'secure.media.serve',
            now()->addMinutes(30),
            ['path' => $alert->video_path]
        );

        return response()->json(['authenticated_stream_target' => $secureUrl], 200);
    }

    /**
     * Streams video segments to ExoPlayer components after signature extraction check verification loops clear.
     */
    public function streamEvidenceFile(Request $request)
    {
        if (!$request->hasValidSignature()) {
            abort(401, 'Cryptographic access link parameter signature token string missing or expired.');
        }

        $path = $request->query('path');
        
        if (!Storage::disk('public')->exists($path)) {
            abort(404);
        }

        return response()->file(storage_path('app/public/' . $path), [
            'Content-Type'        => 'video/mp4',
            'Content-Disposition' => 'inline',
            'Cache-Control'       => 'no-store, private'
        ]);
    }
}
