/**
 * Background Service Worker — Canifa Note
 *
 * 1. Handle SYNC_AUTH from content script (auto-sync Memos token)
 * 2. Handle SAVE_NOTE from content script (call API save memo)
 * 3. Handle REFRESH_TOKEN from popup
 */

import { createMemo } from '../shared/api-client';

/**
 * Grab fresh Memos token from any Canifa Note tab
 */
async function grabFreshToken(): Promise<string | null> {
  try {
    const allTabs = await chrome.tabs.query({});
    const candidates = allTabs.filter((t) => {
      const url = t.url || '';
      return (
        url.includes('172.16.2.210') ||
        url.includes('localhost:5230') ||
        url.includes('cucunote') ||
        url.includes('canifa')
      );
    });

    for (const tab of candidates) {
      if (!tab.id) continue;
      try {
        const results = await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          world: 'MAIN',
          func: () => {
            try {
              // 1. Memos access-token cookie
              const match = document.cookie.match(/(?:^|; )memos\.access-token=([^;]+)/);
              if (match && match[1]) return match[1];

              // 2. localStorage
              for (let i = 0; i < localStorage.length; i++) {
                const key = localStorage.key(i);
                if (key && (key.includes('access_token') || key.includes('token'))) {
                  const val = localStorage.getItem(key);
                  if (val && val.length > 20 && !val.startsWith('{')) return val;
                }
              }
            } catch { /* ignore */ }
            return null;
          },
        });
        const token = results[0]?.result;
        if (token) {
          await chrome.storage.local.set({
            memosAccessToken: token,
            tokenSyncedAt: Date.now(),
          });
          console.log('[Canifa Note] ✅ Token synced from tab', tab.id);
          return token;
        }
      } catch {
        // Try next tab
      }
    }
  } catch {
    // Tab scanning failed
  }
  return null;
}

chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
  // ============ AUTO-SYNC AUTH TOKEN ============
  if (message.type === 'SYNC_AUTH') {
    const token = message.data?.memosAccessToken || message.data?.clerkSessionToken;
    if (token) {
      chrome.storage.local.set({
        memosAccessToken: token,
        tokenSyncedAt: Date.now(),
      });
      console.log('[Canifa Note] ✅ Token auto-synced from content script');
    }
    sendResponse({ success: true });
    return false;
  }

  // ============ REFRESH TOKEN ============
  if (message.type === 'REFRESH_TOKEN') {
    grabFreshToken()
      .then((token) => {
        if (token) {
          sendResponse({ success: true, token });
        } else {
          sendResponse({ success: false, reason: 'no_canifa_note_tab' });
        }
      })
      .catch((err) => {
        sendResponse({ success: false, reason: err?.message });
      });
    return true;
  }

  // ============ SHOW NOTE FORM ============
  if (message.type === 'SHOW_NOTE_FORM') {
    chrome.action.openPopup();
    chrome.storage.local.set({ pendingNote: message.data });
    sendResponse({ success: true });
  }

  // ============ SAVE NOTE ============
  else if (message.type === 'SAVE_NOTE') {
    const { text, url, title } = message.data;

    const domain = new URL(url).hostname.replace('www.', '');
    const tagList = [domain, 'web-highlight'];
    const contentWithSource = `${text}\n\n---\nSource: [${title}](${url})`;

    const memoData = {
      content: contentWithSource,
      tags: tagList,
      visibility: 'PRIVATE',
    };

    createMemo(memoData)
      .then((memo) => {
        sendResponse({ success: true, memo });
      })
      .catch((error) => {
        sendResponse({ success: false, error: error.message });
      });

    return true;
  }

  return true;
});
