// Z-AMPP MAM export target. Replaces raw downloadBlob with a chooser:
// Download (browser save) or Save to MAM (POST to /api/v1/upload/simple).
export type ExportTargetChoice = 'download' | 'mam' | 'cancel';

function resolveProjectId(): string | null {
  try {
    const qs = new URLSearchParams(window.location.search);
    const fromQs = qs.get('project');
    if (fromQs) return fromQs;
    return window.localStorage.getItem('mamProjectId');
  } catch { return null; }
}

export function defaultDownload(blob: Blob, filename: string): void {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = filename;
  document.body.appendChild(a); a.click(); a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 2000);
}

export async function uploadToMAM(blob: Blob, filename: string, contentType: string): Promise<{ assetId?: string; ok: boolean; status: number; body: string; }> {
  const fd = new FormData();
  fd.append('file', blob, filename);
  fd.append('filename', filename);
  fd.append('contentType', contentType || blob.type || 'video/mp4');
  const projectId = resolveProjectId();
  if (projectId) fd.append('projectId', projectId);
  const r = await fetch('/api/v1/upload/simple', { method: 'POST', body: fd, credentials: 'omit' });
  const text = await r.text();
  let assetId: string | undefined;
  try { const j = JSON.parse(text); assetId = j?.id || j?.assetId; } catch {}
  return { assetId, ok: r.ok, status: r.status, body: text };
}
