// ============================================================
// SUPABASE — client + auth/data helpers. Exposed as window.CJSupa.
// The publishable key is public-safe; Row Level Security enforces
// that each user can only read/write their own rows.
// ============================================================
const SB_URL = 'https://veafizelojfbevogjoil.supabase.co';
const SB_PUBLISHABLE_KEY = 'sb_publishable_3roROeEH_itYCpLi0-ySHA_zJOFFFkk';

const _sb = window.supabase.createClient(SB_URL, SB_PUBLISHABLE_KEY);

// ---- row <-> app-shape mappers (see Data/Data-Model) ----
const rowToTrade = (r) => ({
  id: r.id,
  instrument: r.instrument,
  direction: r.direction,
  pnl: r.pnl,
  conf: r.conf || [],
  note: r.note || '',
  shotPaths: r.shot_paths || [],
  ts: new Date(r.ts).getTime(),
});
const tradeToRow = (t, userId) => ({
  user_id: userId,
  instrument: t.instrument,
  direction: t.direction,
  pnl: t.pnl,
  conf: t.conf || [],
  note: t.note || '',
  shot_paths: t.shotPaths || [],
  ts: new Date(t.ts ?? Date.now()).toISOString(),
});

const _uid = async () => {
  const { data } = await _sb.auth.getUser();
  return data.user ? data.user.id : null;
};

window.CJSupa = {
  client: _sb,

  // ---- auth ----
  async getSession() {
    const { data } = await _sb.auth.getSession();
    return data.session;
  },
  onAuthChange(cb) {
    const { data } = _sb.auth.onAuthStateChange((_evt, session) => cb(session));
    return () => data.subscription.unsubscribe();
  },
  async signUp(email, password) {
    const { data, error } = await _sb.auth.signUp({ email, password });
    if (error) return { error: error.message };
    // session is null when "Confirm email" is on — caller must prompt to verify.
    return { ok: true, needsConfirm: !data.session };
  },
  async signIn(email, password) {
    const { error } = await _sb.auth.signInWithPassword({ email, password });
    return error ? { error: error.message } : { ok: true };
  },
  async signInGoogle() {
    const { error } = await _sb.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: window.location.origin + window.location.pathname },
    });
    return error ? { error: error.message } : { ok: true };
  },
  async signOut() {
    await _sb.auth.signOut();
  },
  async resetPassword(email) {
    const { error } = await _sb.auth.resetPasswordForEmail(email, {
      redirectTo: window.location.origin + '/reset',
    });
    return error ? { error: error.message } : { ok: true };
  },
  async updatePassword(password) {
    const { error } = await _sb.auth.updateUser({ password });
    return error ? { error: error.message } : { ok: true };
  },
  async uploadScreenshot(file) {
    const uid = await _uid();
    if (!uid) return null;
    const safe = file.name.replace(/[^\w.\-]/g, '_');
    const path = `${uid}/${Date.now()}-${safe}`;
    const { error } = await _sb.storage.from('screenshots').upload(path, file, { upsert: false });
    if (error) { console.error('uploadScreenshot', error); return null; }
    return path;
  },
  async screenshotUrl(path) {
    if (!path) return null;
    const { data, error } = await _sb.storage.from('screenshots').createSignedUrl(path, 3600);
    if (error) { console.error('screenshotUrl', error); return null; }
    return data.signedUrl;
  },

  // ---- profile ----
  async fetchProfile() {
    const { data, error } = await _sb.from('profiles').select('*').maybeSingle();
    if (error) { console.error('fetchProfile', error); return null; }
    return data; // raw row; the app maps it onto `user`
  },
  async upsertProfile(patch) {
    const id = await _uid();
    if (!id) return false;
    const { error } = await _sb.from('profiles').upsert({ id, ...patch }).eq('id', id);
    if (error) { console.error('upsertProfile', error); return false; }
    return true;
  },

  // ---- trades ----
  async fetchTrades() {
    const { data, error } = await _sb.from('trades').select('*').order('ts', { ascending: false });
    if (error) { console.error('fetchTrades', error); return []; }
    return data.map(rowToTrade);
  },
  async insertTrade(t) {
    const id = await _uid();
    if (!id) return null;
    const { data, error } = await _sb.from('trades').insert(tradeToRow(t, id)).select().single();
    if (error) { console.error('insertTrade', error); return null; }
    return rowToTrade(data);
  },
  async deleteTrade(id) {
    const { error } = await _sb.from('trades').delete().eq('id', id);
    if (error) { console.error('deleteTrade', error); return false; }
    return true;
  },
};
