/* ============================================================
   storage.jsx — Supabase Storage: upload logo + photos
   Bucket: 'tender-assets' (must be created in Supabase dashboard
   with RLS policies allowing authenticated users to write into
   {user_id}/* paths, and public read).
   ============================================================ */

const BUCKET = 'document-assets';
const MAX_SIZE = 5 * 1024 * 1024; // 5 MB
const OK_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/svg+xml'];

async function uploadAsset(file, { docId = 'misc', kind = 'asset', orgId = null } = {}) {
  if (!window.HAS_SUPABASE) {
    // fallback: data URL (works offline, but lives only in localStorage)
    return await fileToDataUrl(file);
  }
  if (!file) throw new Error('Geen bestand');
  if (file.size > MAX_SIZE) throw new Error('Bestand te groot (max 5 MB)');
  if (!OK_TYPES.includes(file.type)) throw new Error('Ongeldig bestandstype');

  const sb = window.getSupabase();
  if (!sb) throw new Error('Supabase niet beschikbaar');

  const { data: { user } } = await sb.auth.getUser();
  if (!user) throw new Error('Niet ingelogd');

  // need orgId for the storage RLS policies
  let org = orgId;
  if (!org) {
    const { data: memRow } = await sb.from('org_members')
      .select('organization_id').limit(1).maybeSingle();
    org = memRow?.organization_id;
  }
  if (!org) throw new Error('Geen organisatie gevonden');

  const ext = (file.name.split('.').pop() || 'png').toLowerCase().replace(/[^a-z0-9]/g, '');
  const path = `${org}/${docId}/${kind}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;

  const { error } = await sb.storage.from(BUCKET).upload(path, file, {
    cacheControl: '3600',
    upsert: false,
    contentType: file.type,
  });
  if (error) throw error;

  // bucket is private → we need signed URL. But public read policy allows anon,
  // so getPublicUrl works for both org members and reviewers.
  const { data } = sb.storage.from(BUCKET).getPublicUrl(path);
  return data.publicUrl;
}

function fileToDataUrl(file) {
  return new Promise((resolve, reject) => {
    const fr = new FileReader();
    fr.onload = () => resolve(fr.result);
    fr.onerror = () => reject(fr.error);
    fr.readAsDataURL(file);
  });
}

async function deleteAsset(url) {
  if (!window.HAS_SUPABASE) return;
  if (!url || url.startsWith('data:')) return;
  const sb = window.getSupabase();
  if (!sb) return;
  // extract path after the bucket name in the public URL
  const idx = url.indexOf(`/${BUCKET}/`);
  if (idx < 0) return;
  const path = url.slice(idx + BUCKET.length + 2);
  await sb.storage.from(BUCKET).remove([path]);
}

Object.assign(window, { uploadAsset, deleteAsset });
