/**
 * Service worker da extensão.
 * Recebe a sessão do content script auth-bridge após o usuário logar
 * no AssinaPro e responde a pings do popup/content scripts.
 */
import { setSession, getSession, isSessionValid } from "./shared/auth.js";
import { fetchSignatures } from "./shared/api.js";

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  (async () => {
    try {
      if (message?.type === "AP_AUTH_TOKEN" && message.session) {
        await setSession(message.session);
        // Fecha a aba do bridge automaticamente.
        if (sender.tab?.id) {
          try { await chrome.tabs.remove(sender.tab.id); } catch { /* noop */ }
        }
        sendResponse({ ok: true });
        return;
      }

      if (message?.type === "AP_GET_SIGNATURES") {
        const session = await getSession();
        if (!isSessionValid(session)) {
          sendResponse({ ok: false, error: "unauthorized" });
          return;
        }
        const signatures = await fetchSignatures(session.access_token);
        sendResponse({ ok: true, signatures });
        return;
      }

      sendResponse({ ok: false, error: "unknown_message" });
    } catch (err) {
      sendResponse({ ok: false, error: err?.message ?? String(err) });
    }
  })();
  // async response
  return true;
});
