// assets/js/flow/upload.js
(function (w) {
  async function afbUploadPacket({ ajaxUrl, requestId, taskGid, file, uploadSig = '', uploadFieldId = '' }) {
    if (!file) return { ok: true, skipped: true };

    const fd = new FormData();
    fd.append('action', 'afb_attach_file');
    fd.append('request_id', requestId);
    fd.append('task_gid', taskGid);
    fd.append('file', file, file.name);
    if (uploadSig) fd.append('upload_sig', String(uploadSig));
    if (uploadFieldId) fd.append('upload_field_id', String(uploadFieldId));

    const res = await fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' });
    const json = await res.json().catch(() => ({}));

    if (!json || json.success !== true) {
      const data = (json && json.data) || {};
      const code = data.http_code || res.status;
      const msg  = data.message || `Upload failed for ${file.name}`;
      throw new Error(`${msg}${code ? ` (HTTP ${code})` : ''}`);
    }
    return json.data || { ok: true };
  }

  w.afbFlowUpload = { afbUploadPacket };
})(window);
