/* Sponzza per-user data (classic content-script global). Uses Supabase REST + Storage. */
var SponzzaDB = (function () {
  function cfg() { return SPONZZA_CONFIG; }
  function uid(session) {
    if (session.user && session.user.id) return session.user.id;
    try {
      var p = session.access_token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
      return JSON.parse(decodeURIComponent(escape(atob(p)))).sub;
    } catch (e) { return null; }
  }
  function authHeaders(session) {
    return {
      'Content-Type': 'application/json',
      'apikey': cfg().SUPABASE_ANON_KEY,
      'Authorization': 'Bearer ' + session.access_token
    };
  }

  // Run a fetch; if the token expired (401), refresh once and retry.
  function withAuth(session, doFetch) {
    return doFetch(session).then(function (r) {
      if (r.status !== 401) return r;
      return SponzzaAuth.refresh().then(function (fresh) { return doFetch(fresh); });
    });
  }

  function logActivity(session, row) {
    row.user_id = uid(session);
    row.updated_at = new Date().toISOString();
    return withAuth(session, function (s) {
      return fetch(cfg().SUPABASE_URL + '/rest/v1/activity?on_conflict=user_id,job_url', {
        method: 'POST',
        headers: Object.assign(authHeaders(s), { 'Prefer': 'resolution=merge-duplicates,return=minimal' }),
        body: JSON.stringify(row)
      });
    }).then(function (r) {
      if (r.ok) return true;
      return r.text().then(function (t) { throw new Error('DB ' + r.status + ': ' + (t || '').slice(0, 160)); });
    });
  }

  function listActivity(session) {
    return withAuth(session, function (s) {
      return fetch(cfg().SUPABASE_URL + '/rest/v1/activity?select=*&order=updated_at.desc&limit=100', {
        headers: authHeaders(s)
      });
    }).then(function (r) { return r.ok ? r.json() : []; });
  }

  function storagePut(session, key, body, contentType) {
    return withAuth(session, function (s) {
      return fetch(cfg().SUPABASE_URL + '/storage/v1/object/resumes/' + encodeURIComponent(key), {
        method: 'POST',
        headers: { 'apikey': cfg().SUPABASE_ANON_KEY, 'Authorization': 'Bearer ' + s.access_token, 'Content-Type': contentType, 'x-upsert': 'true' },
        body: body
      });
    });
  }
  // Save the original PDF + extracted text to the user's private folder.
  function saveResume(session, file, text) {
    var u = uid(session);
    return Promise.all([
      storagePut(session, u + '/cv.pdf', file, file.type || 'application/pdf'),
      storagePut(session, u + '/cv.txt', text, 'text/plain')
    ]).then(function (rs) {
      if (rs[0].ok && rs[1].ok) return true;
      return rs[1].text().then(function (t) { throw new Error('Storage ' + rs[1].status + ': ' + (t || '').slice(0, 120)); });
    });
  }
  // Load the stored résumé text (null if none).
  function loadResumeText(session) {
    var u = uid(session);
    return withAuth(session, function (s) {
      return fetch(cfg().SUPABASE_URL + '/storage/v1/object/resumes/' + encodeURIComponent(u + '/cv.txt'), {
        headers: { 'apikey': cfg().SUPABASE_ANON_KEY, 'Authorization': 'Bearer ' + s.access_token }
      });
    }).then(function (r) { return r.ok ? r.text() : null; }).catch(function () { return null; });
  }

  function updateActivity(session, jobUrl, patch) {
    return withAuth(session, function (s) {
      var q = encodeURIComponent('job_url=eq.' + jobUrl + '&user_id=eq.' + uid(session));
      return fetch(cfg().SUPABASE_URL + '/rest/v1/activity?' + q, {
        method: 'PATCH',
        headers: Object.assign(authHeaders(s), { 'Prefer': 'return=minimal' }),
        body: JSON.stringify(patch)
      });
    }).then(function (r) {
      if (r.ok) return true;
      return r.text().then(function (t) { throw new Error('DB ' + r.status + ': ' + (t || '').slice(0, 120)); });
    });
  }

  return { logActivity: logActivity, listActivity: listActivity, updateActivity: updateActivity, saveResume: saveResume, loadResumeText: loadResumeText };
})();
