/* Sponzza background service worker — handles Google OAuth via chrome.identity. */
importScripts('src/config.js');

function parseFragment(url) {
  var frag = url.split('#')[1] || '';
  var p = new URLSearchParams(frag);
  return { access_token: p.get('access_token'), refresh_token: p.get('refresh_token'), expires_at: p.get('expires_at') };
}

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
  if (msg && msg.type === 'sponzza-google') {
    var redirect = chrome.identity.getRedirectURL();
    var authUrl = SPONZZA_CONFIG.SUPABASE_URL + '/auth/v1/authorize?provider=google&redirect_to=' +
      encodeURIComponent(redirect);
    chrome.identity.launchWebAuthFlow({ url: authUrl, interactive: true }, function (resultUrl) {
      if (chrome.runtime.lastError || !resultUrl) {
        sendResponse({ ok: false, error: (chrome.runtime.lastError && chrome.runtime.lastError.message) || 'cancelled' });
        return;
      }
      var t = parseFragment(resultUrl);
      if (!t.access_token) { sendResponse({ ok: false, error: 'no token returned' }); return; }
      // Fetch the user to get the email.
      fetch(SPONZZA_CONFIG.SUPABASE_URL + '/auth/v1/user', {
        headers: { apikey: SPONZZA_CONFIG.SUPABASE_ANON_KEY, Authorization: 'Bearer ' + t.access_token }
      }).then(function (r) { return r.json(); }).then(function (u) {
        var session = { access_token: t.access_token, refresh_token: t.refresh_token, expires_at: t.expires_at, user: { email: u.email, id: u.id } };
        chrome.storage.local.set({ sponzza_session: session }, function () { sendResponse({ ok: true, session: session }); });
      }).catch(function () { sendResponse({ ok: false, error: 'user lookup failed' }); });
    });
    return true; // async
  }
});
