/**
 * API Client - Gọi backend CuCu Note
 * Reuse logic từ frontend nếu có thể
 */

// Default API base URL - can be overridden via chrome.storage
// In production, this should be set via extension settings or build-time config
const DEFAULT_API_BASE_URL = 'http://localhost:5000';

// Lấy API base từ storage hoặc dùng default
async function getApiBase(): Promise<string> {
  const result = await chrome.storage.local.get(['apiBaseUrl']);
  const baseUrl = result.apiBaseUrl || DEFAULT_API_BASE_URL;
  return `${baseUrl}/api/v1`;
}

// Export để có thể set từ popup/settings
export async function setApiBaseUrl(url: string): Promise<void> {
  await chrome.storage.local.set({ apiBaseUrl: url });
}

export interface CreateMemoRequest {
  content: string;
  tags?: string[];
  visibility?: string;
}

export interface MemoResponse {
  id: string;
  content: string;
  tags: string[];
  created_at: string;
}

export async function createMemo(data: CreateMemoRequest): Promise<MemoResponse> {
  const token = await getAuthToken();
  const apiBase = await getApiBase();

  // Debug: Log token status (không log full token vì security)
  if (token) {
    console.log('[CuCu Note] ✅ Auth token found, length:', token.length);
  } else {
    console.warn('[CuCu Note] ⚠️ No auth token found! Request will be unauthenticated.');
  }

  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
  };

  // Gửi Clerk token trong Authorization header (format: Bearer <token>)
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const response = await fetch(`${apiBase}/memos`, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      content: data.content,
      tags: data.tags || [],
      visibility: data.visibility || 'PRIVATE',
    }),
  });

  if (!response.ok) {
    const error = await response.text();
    console.error('[CuCu Note] ❌ API Error:', response.status, error);
    throw new Error(`Failed to create memo: ${error}`);
  }

  const result = await response.json();
  console.log('[CuCu Note] ✅ Memo saved successfully:', result.id);
  return result;
}

async function getAuthToken(): Promise<string | null> {
  // Lấy Clerk session token từ storage
  // Frontend có thể lưu token vào chrome.storage.local khi user login
  const result = await chrome.storage.local.get(['clerkSessionToken', 'authToken']);
  
  // Ưu tiên Clerk token
  if (result.clerkSessionToken) {
    return result.clerkSessionToken;
  }
  
  // Fallback về authToken cũ
  return result.authToken || null;
}

/**
 * Lấy Clerk token từ frontend page (nếu đang ở trang frontend)
 * Inject script vào page để access window.Clerk
 */
export async function syncClerkTokenFromPage(): Promise<string | null> {
  try {
    // Inject script vào page để lấy Clerk token
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab.id) return null;
    
    const results = await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      func: async () => {
        // Access window.Clerk từ page context
        if (typeof window !== 'undefined' && (window as any).Clerk?.session?.getToken) {
          try {
            const token = await (window as any).Clerk.session.getToken();
            return token || null;
          } catch {
            return null;
          }
        }
        return null;
      },
    });
    
    const token = results[0]?.result || null;
    if (token) {
      // Lưu token vào storage
      await chrome.storage.local.set({ clerkSessionToken: token });
    }
    return token;
  } catch (error) {
    console.error('[CuCu Note] Error syncing Clerk token:', error);
    return null;
  }
}

export async function setAuthToken(token: string): Promise<void> {
  await chrome.storage.local.set({ authToken: token });
}

