// Shared asset-upload helper — real presigned R2 upload through the gateway.
//
// Replaces the old setTimeout placeholder "uploads" in VideoMediaBlock /
// CompanionSlot (field-widgets.jsx) and BackgroundPicker / MediaSlot
// (editors.jsx). Returns an `asset://<id>` reference the layout draft stores.
//
// Flow (PUT-then-POST, same shape the export surface uses):
//   1. POST  /v1/courses/:courseId/assets/upload-url     → { assetId, uploadUrl }
//   2. PUT   <uploadUrl> (R2 presigned)                  → 200
//   3. POST  /v1/courses/:courseId/assets/upload-complete → { ref: 'asset://<id>' }
//
// Wrapped in an IIFE so the module-level `GATEWAY_BASE` const does NOT collide
// with the identically-named top-level const in surface-export.jsx (classic
// <script> bodies share one global lexical environment here). Only
// `window.uploadAsset` is exposed.
(function () {
  // Environment-aware gateway host (see src/env-config.js). Mirrors surface-export.jsx.
  const GATEWAY_BASE = window.DYNAMO_ENV.gatewayBase;

  async function uploadAsset(courseId, file, kind) {
    const token = await window.dynamoGetAccessToken();
    const authJson = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
    const r1 = await fetch(`${GATEWAY_BASE}/v1/courses/${courseId}/assets/upload-url`, {
      method: 'POST', headers: authJson,
      body: JSON.stringify({ filename: file.name, mime: file.type, kind, sizeBytes: file.size }),
    });
    if (!r1.ok) throw new Error(`upload-url ${r1.status}`);
    const { assetId, uploadUrl } = await r1.json();
    const put = await fetch(uploadUrl, { method: 'PUT', headers: { 'Content-Type': file.type }, body: file });
    if (!put.ok) throw new Error(`R2 PUT ${put.status}`);
    const r2 = await fetch(`${GATEWAY_BASE}/v1/courses/${courseId}/assets/upload-complete`, {
      method: 'POST', headers: authJson,
      body: JSON.stringify({ assetId, filename: file.name, mime: file.type, kind }),
    });
    if (!r2.ok) throw new Error(`upload-complete ${r2.status}`);
    return (await r2.json()).ref; // 'asset://<id>'
  }

  window.uploadAsset = uploadAsset;
  // Seeded fallback (matches the export surface's UUID fallback) so uploads
  // resolve a valid course id even before app.jsx sets the live one.
  window.dynamoCourseId = window.dynamoCourseId || '7bf69e2d-51e7-4856-86bb-bb2b77b47216';
})();
