// PocketBase auth bootstrap shared by pages
(function (global) {
  const pb = new PocketBase('https://pocketbase.ccllc.pro');
  const GRAPH_TOKEN_KEY = 'graphAccessToken';
  const USER_ID_KEY = 'userId';

  function authHeaders() {
    if (pb.authStore.isValid && pb.authStore.token) {
      return { Authorization: `Bearer ${pb.authStore.token}` };
    }
    return {};
  }

  function getDisplayName() {
    const model = pb.authStore.model || {};
    return (
      model.display_name ||
      model.name ||
      model.email ||
      model.username ||
      'Unknown'
    );
  }

  function getEmail() {
    const model = pb.authStore.model || {};
    return model.email || model.username || null;
  }

  function getUserId() {
    return pb.authStore.model?.id || localStorage.getItem(USER_ID_KEY) || null;
  }

  // Get Graph token - first from localStorage, then try to refresh from backend
  async function getGraphToken() {
    // First check localStorage
    let token = localStorage.getItem(GRAPH_TOKEN_KEY);
    
    // If we have a valid PB session but no graph token, try to get from backend
    if (!token && pb.authStore.isValid) {
      try {
        const response = await fetch('/api/auth/refresh-token?type=graph', {
          headers: authHeaders()
        });
        if (response.ok) {
          const data = await response.json();
          if (data.token) {
            token = data.token;
            localStorage.setItem(GRAPH_TOKEN_KEY, token);
            console.log('[Auth] Got Graph token from backend cache');
          }
        }
      } catch (err) {
        console.warn('[Auth] Could not get Graph token from backend:', err);
      }
    }
    
    return token;
  }

  // Synchronous version for backwards compatibility
  function getGraphTokenSync() {
    return localStorage.getItem(GRAPH_TOKEN_KEY);
  }

  async function ensureAuth() {
    if (pb.authStore.isValid) {
      // Try to refresh tokens from backend on page load
      try {
        await refreshTokensFromBackend();
      } catch (err) {
        console.warn('[Auth] Token refresh failed:', err);
      }
      return true;
    }
    const path = new URL(window.location.href).pathname;
    if (!path.endsWith('signin.html')) {
      window.location.href = 'signin.html';
    }
    return false;
  }

  // Refresh tokens from backend cache
  async function refreshTokensFromBackend() {
    if (!pb.authStore.isValid) return;

    const userId = getUserId();
    if (!userId) return;

    try {
      // Get fresh Graph token from backend
      const response = await fetch('/api/auth/refresh-token?type=graph', {
        headers: authHeaders()
      });
      
      if (response.ok) {
        const data = await response.json();
        if (data.token) {
          localStorage.setItem(GRAPH_TOKEN_KEY, data.token);
          console.log('[Auth] Refreshed Graph token from backend, source:', data.source);
        }
      } else if (response.status === 401) {
        // Token expired or invalid in backend, but we might still have a valid PB session
        // Try to re-store our current tokens
        console.log('[Auth] Backend token expired, attempting to re-store');
        await restoreTokensToBackend();
      }
    } catch (err) {
      console.warn('[Auth] Token refresh error:', err);
    }
  }

  // Re-store tokens to backend (in case backend cache was cleared)
  async function restoreTokensToBackend() {
    if (!pb.authStore.isValid) return;

    try {
      // Refresh PocketBase auth to potentially get a new Graph token
      const authData = await pb.collection('users').authRefresh();
      
      const graphToken = extractGraphToken(authData) || localStorage.getItem(GRAPH_TOKEN_KEY);
      
      if (graphToken) {
        const response = await fetch('/api/auth/login-callback', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            ...authHeaders()
          },
          body: JSON.stringify({
            pbToken: pb.authStore.token,
            graphToken: graphToken,
            refreshTokenPb: '',
            refreshTokenGraph: authData?.meta?.refreshToken || '',
            user: {
              id: pb.authStore.model?.id,
              email: pb.authStore.model?.email,
              name: pb.authStore.model?.name || pb.authStore.model?.display_name
            }
          })
        });

        if (response.ok) {
          console.log('[Auth] Re-stored tokens in backend');
        }
      }
    } catch (err) {
      console.warn('[Auth] Failed to re-store tokens:', err);
    }
  }

  function extractGraphToken(authData) {
    return (
      authData?.meta?.graphAccessToken ||
      authData?.meta?.graph_token ||
      authData?.meta?.graphToken ||
      authData?.meta?.accessToken ||
      authData?.meta?.access_token ||
      authData?.meta?.token ||
      authData?.meta?.rawToken ||
      authData?.meta?.authData?.access_token ||
      ''
    );
  }

  global.Auth = { 
    pb, 
    authHeaders, 
    ensureAuth, 
    getDisplayName, 
    getEmail, 
    getUserId,
    getGraphToken,
    getGraphTokenSync,
    refreshTokensFromBackend,
    restoreTokensToBackend,
    extractGraphToken,
    GRAPH_TOKEN_KEY,
    USER_ID_KEY
  };
})(window);
