importScripts("../src/lib/biliindex-core.js");

chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.local.set({ apiBase: BiliIndex.DEFAULT_API_BASE });
  preloadTags();
});

chrome.runtime.onStartup.addListener(() => {
  preloadTags();
});

async function preloadTags() {
  try {
    await BiliIndex.refreshTagCaches(false);
  } catch (e) {
    console.warn("[BiliIndex] 标签预加载失败", e.message);
  }
}

chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
  if (msg.type === "FETCH_PUBLIC") {
    BiliIndex._fetchPublicDirect(msg.path)
      .then((data) => sendResponse({ ok: true, data }))
      .catch((e) => sendResponse({ ok: false, error: e.message }));
    return true;
  }
  if (msg.type === "API_FETCH") {
    BiliIndex._apiFetchDirect(msg.path, msg.options || {})
      .then((data) => sendResponse({ ok: true, data }))
      .catch((e) => sendResponse({ ok: false, error: e.message }));
    return true;
  }
  if (msg.type === "REFRESH_TAGS") {
    BiliIndex.refreshTagCaches(true)
      .then(({ tree, quick }) =>
        sendResponse({ ok: true, tree, quick, items: quick })
      )
      .catch((e) => sendResponse({ ok: false, error: e.message, items: [] }));
    return true;
  }
  if (msg.type === "GET_TAG_TREE") {
    BiliIndex.getTagTree(!!msg.force)
      .then((tree) => sendResponse({ ok: true, items: tree }))
      .catch((e) => sendResponse({ ok: false, error: e.message, items: [] }));
    return true;
  }
  if (msg.type === "GET_QUICK_TAGS") {
    BiliIndex.getQuickTags(!!msg.force)
      .then((items) => sendResponse({ ok: true, items: items || [] }))
      .catch((e) => sendResponse({ ok: false, error: e.message, items: [] }));
    return true;
  }
  if (msg.type === "QUICK_TAG") {
    BiliIndex.quickTag(msg.up_mid, msg.tag_code, {
      slot: msg.slot || "tag1",
      nickname: msg.nickname,
      fan_count: msg.fan_count,
    })
      .then((res) => sendResponse(res))
      .catch((e) => sendResponse({ ok: false, error: e.message }));
    return true;
  }
  if (msg.type === "SUBMIT_TAG") {
    BiliIndex.submitTag(msg.up_mid, msg.tag_id)
      .then((res) => sendResponse(res))
      .catch((e) => sendResponse({ ok: false, error: e.message }));
    return true;
  }
  if (msg.type === "GET_AUTH") {
    Promise.all([BiliIndex.getToken(), BiliIndex.storageGet(["user"])])
      .then(([token, { user }]) => sendResponse({ token, user }))
      .catch((e) => sendResponse({ token: null, user: null, error: e.message }));
    return true;
  }
});
