// kir0Qual V2 background service worker.
// The optimizer engine is intentionally not imported or modified here.

const API_BASE = 'https://kir0qual-api.kir0qual.workers.dev';

chrome.runtime.onInstalled.addListener(() => {
  console.log('[kir0Qual] V2 service worker installed');
});

async function api(path, options = {}) {
  const response = await fetch(API_BASE + path, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...(options.headers || {})
    }
  });

  let body = null;
  try { body = await response.json(); } catch (_) {}

  if (!response.ok) {
    throw new Error(body?.error || `Backend request failed (${response.status})`);
  }
  return body;
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (!message || typeof message.type !== 'string') return;

  (async () => {
    switch (message.type) {
      case 'KIR0_PING':
        return { ok: true, version: 'V2' };

      case 'KIR0_BACKEND_STATUS':
        try {
          const result = await api('/health');
          return { ok: true, backendConfigured: true, backend: result };
        } catch (error) {
          return { ok: false, backendConfigured: false, error: error.message };
        }

      case 'KIR0_AUTH_DISCORD':
        return api('/api/auth/discord/exchange', {
          method: 'POST',
          body: JSON.stringify({
            code: message.code,
            codeVerifier: message.codeVerifier,
            redirectUri: message.redirectUri
          })
        });

      case 'KIR0_SESSION':
        return api('/api/session', {
          method: 'POST',
          body: JSON.stringify({ sessionToken: message.sessionToken })
        });

      case 'KIR0_LOGOUT':
        return api('/api/session/logout', {
          method: 'POST',
          body: JSON.stringify({ sessionToken: message.sessionToken })
        });

      case 'KIR0_QUOTA_RESERVE':
        return api('/api/quota/reserve', {
          method: 'POST',
          body: JSON.stringify({ sessionToken: message.sessionToken })
        });

      case 'KIR0_QUOTA_COMMIT':
        return api('/api/quota/commit', {
          method: 'POST',
          body: JSON.stringify({
            sessionToken: message.sessionToken,
            reservationId: message.reservationId
          })
        });

      case 'KIR0_CLEAR_TIKTOK_DATA':
        await chrome.browsingData.remove({origins: ['https://www.tiktok.com', 'https://tiktok.com']}, {cookies:true,localStorage:true,indexedDB:true,cacheStorage:true,serviceWorkers:true});
        const tabs = await chrome.tabs.query({url: ['https://www.tiktok.com/*', 'https://tiktok.com/*', 'https://*.tiktok.com/*']});
        await Promise.all(tabs.map(tab => chrome.tabs.reload(tab.id).catch(() => {})));
        return {ok:true, reloaded:tabs.length};

      case 'KIR0_SET_SIGNAL':
        await chrome.storage.local.set({kir0SignalEnabled: !!message.enabled});
        return {ok:true, enabled:!!message.enabled};

      case 'KIR0_QUOTA_RELEASE':
        return api('/api/quota/release', {
          method: 'POST',
          body: JSON.stringify({
            sessionToken: message.sessionToken,
            reservationId: message.reservationId
          })
        });

      default:
        throw new Error(`Unknown message type: ${message.type}`);
    }
  })()
    .then(result => sendResponse(result))
    .catch(error => sendResponse({ ok: false, error: error.message }));

  return true;
});
