<?php

namespace App\Http\Controllers\Communication;

use App\Http\Controllers\Controller;
use App\Models\Communication\Recording;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;

class RecordingStreamController extends Controller {
    public function __invoke(Request $request, Recording $recording): mixed {

        Gate::authorize('view', $recording);

        // ── Locally stored file ───────────────────────────────────────────────
        if ($recording->hasStoredFile()) {
            $disk = Storage::disk($recording->storage_disk);

            abort_unless($disk->exists($recording->storage_path), 404);

            $mimeType = $disk->mimeType($recording->storage_path) ?: 'audio/mpeg';
            $size = $disk->size($recording->storage_path);

            return response()->stream(function () use ($disk, $recording)
            {
                $stream = $disk->readStream($recording->storage_path);
                fpassthru($stream);
                if (is_resource($stream)) {
                    fclose($stream);
                }
            }, 200, [
                'Content-Type' => $mimeType,
                'Content-Length' => $size,
                'Content-Disposition' => 'inline',
                'Accept-Ranges' => 'bytes',
                'Cache-Control' => 'private, max-age=3600',
            ]);
        }

        // ── External URL (e.g. Twilio CDN) ────────────────────────────────────
        if (filled($recording->recording_url)) {
            return redirect($recording->recording_url);
        }

        abort(404);
    }
}
