/**
 * Helpers de sessão persistidos em chrome.storage.local.
 * A sessão é o próprio JWT do Supabase que o usuário obteve ao logar no AssinaPro.
 */
import { STORAGE_KEYS } from "./config.js";

export async function getSession() {
  const out = await chrome.storage.local.get(STORAGE_KEYS.session);
  return out[STORAGE_KEYS.session] ?? null;
}

export async function setSession(session) {
  await chrome.storage.local.set({ [STORAGE_KEYS.session]: session });
}

export async function clearSession() {
  await chrome.storage.local.remove([STORAGE_KEYS.session, STORAGE_KEYS.activeSignatureId]);
}

export async function getActiveSignatureId() {
  const out = await chrome.storage.local.get(STORAGE_KEYS.activeSignatureId);
  return out[STORAGE_KEYS.activeSignatureId] ?? null;
}

export async function setActiveSignatureId(id) {
  await chrome.storage.local.set({ [STORAGE_KEYS.activeSignatureId]: id });
}

export function isSessionValid(session) {
  if (!session || !session.access_token) return false;
  if (session.expires_at && Date.now() / 1000 > session.expires_at) return false;
  return true;
}
