/* ═══════════════════════════════════════════════════════
   lib/firebase · Auth REST + RTDB REST helpers
═══════════════════════════════════════════════════════ */

/* Pinned credentials — change here if migrating projects. */
const FB_RTDB   = 'https://raisedeploy-fdabd-default-rtdb.firebaseio.com';
const FB_APIKEY = 'AIzaSyAaOGqYCzyktUSNkTcrx-Hra56l2mxijHo';
const APP_VERSION = '2.6.0';

/* ── Auth (stored in localStorage) ──────────────────── */
function fbStoreAuth(token, email, expiresIn, uid, refreshToken) {
  const payload = {
    token, email, uid,
    expiresAt: Date.now() + (Number(expiresIn) || 3600) * 1000,
    refreshToken: refreshToken || null,
  };
  try { localStorage.setItem('scp_auth', JSON.stringify(payload)); } catch (e) {}
  return payload;
}

/* ── Refresh expired token automatically ─────── */
function fbRefreshToken(refreshToken) {
  return fetch('https://securetoken.googleapis.com/v1/token?key=' + FB_APIKEY, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'grant_type=refresh_token&refresh_token=' + encodeURIComponent(refreshToken),
  }).then(r => r.json()).then(d => {
    if (d.error) throw new Error('Refresh falhou: ' + d.error.message);
    // d.id_token, d.user_id, d.expires_in, d.refresh_token
    const auth = fbStoreAuth(d.id_token, null, d.expires_in, d.user_id, d.refresh_token);
    return auth;
  });
}

function fbGetStoredAuth() {
  try {
    const a = JSON.parse(localStorage.getItem('scp_auth') || 'null');
    if (!a || !a.token) return null;
    // Token still valid
    if (a.expiresAt > Date.now() + 60000) return a; // 1min buffer
    // Token expired but we have a refresh token — caller handles async refresh
    if (a.refreshToken) return { ...a, needsRefresh: true };
    return null;
  } catch (e) {}
  return null;
}
function fbClearAuth() {
  try { localStorage.removeItem('scp_auth'); } catch (e) {}
}
const authURL = path => `https://identitytoolkit.googleapis.com/v1/accounts:${path}?key=${FB_APIKEY}`;
function fbLogin(email, pw) {
  return fetch(authURL('signInWithPassword'), {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password: pw, returnSecureToken: true }),
  }).then(r => r.json()).then(d => {
    if (d.error) {
      const m = d.error.message || '';
      if (m.includes('INVALID_LOGIN') || m === 'EMAIL_NOT_FOUND' || m === 'INVALID_PASSWORD' || m === 'INVALID_EMAIL') throw new Error('E-mail ou senha incorretos');
      if (m.includes('TOO_MANY')) throw new Error('Muitas tentativas. Aguarde alguns minutos.');
      throw new Error('Erro: ' + m);
    }
    return d;
  });
}
function fbRegister(email, pw) {
  return fetch(authURL('signUp'), {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password: pw, returnSecureToken: true }),
  }).then(r => r.json()).then(d => {
    if (d.error) {
      const m = d.error.message || '';
      if (m === 'EMAIL_EXISTS') throw new Error('E-mail já cadastrado');
      if (m.includes('WEAK_PASSWORD')) throw new Error('Senha fraca — mínimo 6 caracteres');
      if (m === 'INVALID_EMAIL') throw new Error('E-mail inválido');
      throw new Error('Erro: ' + m);
    }
    return d;
  });
}
function fbChangePw(token, newPw) {
  return fetch(authURL('update'), {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ idToken: token, password: newPw, returnSecureToken: true }),
  }).then(r => r.json()).then(d => {
    if (d.error) throw new Error('Erro: ' + (d.error.message || ''));
    return d;
  });
}
function fbRecoverPw(email) {
  return fetch(authURL('sendOobCode'), {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ requestType: 'PASSWORD_RESET', email }),
  }).then(r => r.json()).then(d => {
    if (d.error) {
      const m = d.error.message || '';
      if (m === 'EMAIL_NOT_FOUND') throw new Error('E-mail não cadastrado');
      throw new Error('Erro: ' + m);
    }
    return d;
  });
}

/* ── RTDB REST helpers ───────────────────────────────── */
function getToken() {
  const a = fbGetStoredAuth();
  return a?.token || S.token || null;
}
function dbURL(path) {
  const tok = getToken();
  return FB_RTDB + path + (tok ? '?auth=' + tok : '');
}

// Internal fetch with auto token refresh on 401
function _dbFetch(path, opts, retry = true) {
  return fetch(dbURL(path), opts).then(r => {
    if (r.status === 401) {
      const stored = fbGetStoredAuth();
      if (retry && stored && stored.refreshToken) {
        return fbRefreshToken(stored.refreshToken).then(newAuth => {
          // Update S.token with fresh token
          if (window.S) { S.token = newAuth.token; }
          return _dbFetch(path, opts, false); // retry once
        }).catch(() => {
          fbClearAuth();
          throw Object.assign(new Error('Sessão expirada'), { auth: true });
        });
      }
      fbClearAuth();
      throw Object.assign(new Error('Sessão expirada'), { auth: true });
    }
    return r;
  });
}
function dbGet(path) {
  return _dbFetch(path, {}).then(r => r.json());
}
function dbPut(path, data) {
  return _dbFetch(path, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  }).then(r => {
    if (r.status === 403) throw new Error('Sem permissão');
    return r.json();
  });
}
function dbPatch(path, data) {
  return _dbFetch(path, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  }).then(r => {
    if (r.status === 403) throw new Error('Sem permissão');
    return r.json();
  });
}
function dbPost(path, data) {
  return _dbFetch(path, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  }).then(r => r.json());
}
function dbDelete(path) {
  return _dbFetch(path, { method: 'DELETE' }).then(() => null);
}

/* Debounced save (used for chip-counting / buy-in changes) */
let _saveTimer = null;
function debouncedSave(path, data, delay = 1000) {
  clearTimeout(_saveTimer);
  return new Promise(resolve => {
    _saveTimer = setTimeout(() => {
      dbPut(path, data).then(resolve).catch(() => resolve());
    }, delay);
  });
}

Object.assign(window, {
  FB_RTDB, FB_APIKEY, APP_VERSION,
  fbGetStoredAuth, fbStoreAuth, fbClearAuth, fbRefreshToken,
  fbLogin, fbRegister, fbChangePw, fbRecoverPw,
  dbGet, dbPut, dbPatch, dbPost, dbDelete, debouncedSave,
});
