// Tempo — account & data management (GDPR: reset journal, delete account)
// All Supabase calls go through window.sb. Exposes window.resetMyData / window.deleteMyAccount.
//
// Storage layout (see state.jsx → uploadDayAttachment): files live at
//   {uid}/{date}/{timestamp}_{filename}
// So we list the user's top-level folder, then list each date subfolder to
// collect every object path, and remove them in batches.

const BUCKET = 'day-attachments';

// Collect every storage object path under a given prefix (one level of nesting:
// {uid}/{date}/{file}). Returns an array of full paths ready for .remove().
async function _collectAttachmentPaths(uid) {
  const paths = [];
  // Top level under {uid}/ → entries are date folders (and possibly stray files).
  const { data: top, error: topErr } = await window.sb.storage
    .from(BUCKET).list(uid, { limit: 1000 });
  if (topErr || !top) return paths;
  for (const entry of top) {
    if (!entry || !entry.name) continue;
    // A "folder" entry has no id/metadata; a real file has metadata.
    const isFile = !!(entry.id || entry.metadata);
    if (isFile) {
      paths.push(`${uid}/${entry.name}`);
      continue;
    }
    // It's a date folder — list its contents.
    const sub = `${uid}/${entry.name}`;
    const { data: inner, error: innerErr } = await window.sb.storage
      .from(BUCKET).list(sub, { limit: 1000 });
    if (innerErr || !inner) continue;
    for (const f of inner) {
      if (f && f.name) paths.push(`${sub}/${f.name}`);
    }
  }
  return paths;
}

// Returns {error} or {ok:true}
async function resetMyData() {
  const { data: u } = await window.sb.auth.getUser();
  const uid = u?.user?.id;
  if (!uid) return { error: { message: 'Non connecté.' } };

  // 1) Delete storage files first (best-effort — never block DB wipe on storage).
  try {
    const paths = await _collectAttachmentPaths(uid);
    // Remove in batches of 100 to stay well under API limits.
    for (let i = 0; i < paths.length; i += 100) {
      const batch = paths.slice(i, i + 100);
      if (batch.length) await window.sb.storage.from(BUCKET).remove(batch);
    }
  } catch (e) { /* storage cleanup is best-effort */ }

  // 2) Delete DB rows. Order matters for FKs: child rows before parents.
  //    (completions reference habits; trades may reference strategies;
  //     backtest_trades reference backtest_sessions.)
  const tables = [
    'habit_completions', 'day_attachments', 'day_journals', 'agenda_events',
    'trades', 'habits',
    'backtest_trades', 'backtest_sessions', 'strategies',
  ];
  for (const t of tables) {
    const { error } = await window.sb.from(t).delete().eq('user_id', uid);
    if (error) return { error };
  }
  return { ok: true };
}

// Best-effort: deprovision every MetaApi connection via the broker worker
// before wiping broker_connections. Never blocks account deletion (the worker
// may be unreachable or not deployed — the rows are removed regardless).
async function _disconnectBrokers(uid) {
  try {
    const { data: conns } = await window.sb.from('broker_connections').select('id').eq('user_id', uid);
    if (!conns || !conns.length) return;
    const { data: s } = await window.sb.auth.getSession();
    const token = s?.session?.access_token;
    if (!token) return;
    const base = String(window.BROKER_WORKER_DEFAULT || '').replace(/\/+$/, '');
    if (!base) return;
    for (const c of conns) {
      try {
        await fetch(base + '/disconnect', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
          body: JSON.stringify({ connectionId: c.id }),
        });
      } catch (e) { /* best-effort per connection */ }
    }
  } catch (e) { /* best-effort */ }
}

// Full account erasure: wipe all personal data, delete the profile row, sign out.
// NOTE: removing the auth.users row itself requires a service-role Edge Function
// (the anon client cannot delete auth users). Wiping ALL personal data + signing
// out satisfies GDPR data-erasure; the residual auth record (email only) can be
// purged server-side on request.
async function deleteMyAccount() {
  const { data: u0 } = await window.sb.auth.getUser();
  const uid0 = u0?.user?.id;
  // Deprovision MetaApi first (needs the session), then wipe data + connections.
  if (uid0) await _disconnectBrokers(uid0);
  const r = await resetMyData();
  if (r.error) return r;
  const { data: u } = await window.sb.auth.getUser();
  const uid = u?.user?.id;
  try { if (uid) await window.sb.from('broker_connections').delete().eq('user_id', uid); } catch (e) {}
  try { if (uid) await window.sb.from('profiles').delete().eq('id', uid); } catch (e) {}
  try { localStorage.clear(); } catch (e) {}
  try { await window.sb.auth.signOut(); } catch (e) {}
  return { ok: true };
}

Object.assign(window, { resetMyData, deleteMyAccount });
