<?php

namespace Modules\GuidedTour\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Modules\GuidedTour\Entities\TourMedia;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
 * Streams tour media from a PRIVATE disk. Hardened against casual download and
 * download managers (IDM etc.):
 *   - route is `signed` + short-TTL, so a copied URL expires fast
 *   - same-origin Referer/Origin check
 *   - Range requests are rejected (416) and Accept-Ranges: none, which defeats
 *     the segmented/multi-connection downloads IDM relies on
 *   - Content-Disposition: inline + no-store, so browsers don't offer "Save as"
 *
 * Honest limit: this cannot stop screen recording. No DRM is claimed.
 */
class MediaController extends Controller
{
    public function stream(Request $request, TourMedia $media): StreamedResponse
    {
        // 1. Same-origin only — block hotlinking / external fetchers.
        $origin = $request->headers->get('origin') ?: $request->headers->get('referer');
        if ($origin && ! str_starts_with($origin, $request->getSchemeAndHttpHost())) {
            abort(403);
        }

        // 2. No range/partial requests — kills segmented download managers.
        if ($request->headers->has('range')) {
            abort(416); // Range Not Satisfiable
        }

        $disk = Storage::disk($media->disk ?: config('guidedtour.media_disk', 'local'));
        if (! $disk->exists($media->path)) {
            abort(404);
        }

        $mime = $media->mime ?: 'application/octet-stream';

        return response()->stream(function () use ($disk, $media) {
            $stream = $disk->readStream($media->path);
            if ($stream === false) {
                return;
            }
            fpassthru($stream);
            if (is_resource($stream)) {
                fclose($stream);
            }
        }, 200, [
            'Content-Type'        => $mime,
            'Content-Disposition' => 'inline',
            'Accept-Ranges'       => 'none',
            'Cache-Control'       => 'no-store, private, max-age=0',
            'Pragma'              => 'no-cache',
            'X-Content-Type-Options' => 'nosniff',
        ]);
    }
}
