import 'dart:html' as html;
import 'dart:typed_data';

Future<Map<String, Object>> prepareNewsVideoSource(
  String url,
  Map<String, String> headers,
) async {
  // Browser video tags cannot send the app's bearer header. Fetch the
  // protected file once with authorization, then hand the player a Blob URL.
  final request = await html.HttpRequest.request(
    url,
    method: 'GET',
    requestHeaders: headers,
    responseType: 'arraybuffer',
  ).timeout(const Duration(seconds: 30));

  if (request.status == null || request.status! < 200 || request.status! >= 300) {
    throw Exception('Video request failed (HTTP ${request.status ?? 0}).');
  }

  final raw = request.response;
  final bytes = raw is ByteBuffer
      ? Uint8List.view(raw)
      : raw is Uint8List
          ? raw
          : null;
  if (bytes == null || bytes.isEmpty) {
    throw Exception('The server returned an empty video file.');
  }
  if (bytes.length > 32 * 1024 * 1024) {
    throw Exception('This video is too large to prepare for browser playback.');
  }

  final mimeType = request.getResponseHeader('content-type') ?? 'video/mp4';
  final blob = html.Blob([bytes], mimeType);
  final blobUrl = html.Url.createObjectUrlFromBlob(blob);
  return {
    'url': blobUrl,
    'headers': <String, String>{},
    'temporary': true,
    // A second tap starts playback within the browser's user gesture window.
    'requiresTap': true,
  };
}

void releaseNewsVideoSource(String? url) {
  if (url != null && url.startsWith('blob:')) html.Url.revokeObjectUrl(url);
}
