/**
 * Redirect from idp-auth logout page back to SimulENT login
 * v1.3.7
 *
 * Runs at document_start for maximum speed — must redirect before
 * the page has time to do its own redirect or clear the console.
 */

(function() {
  'use strict';

  const LOGIN_URL = 'https://simulent.partenaire.test-gar.education.fr/auth/login';

  async function tryRedirect() {
    try {
      const data = await chrome.runtime.sendMessage({ action: 'getCredentials' });
      if (!data || !data.garfill_credentials) return;

      const age = Date.now() - (data.garfill_timestamp || 0);
      if (age > 120000) return;

      console.log('[GAR Autofill] 🔄 Redirect logout → login');
      window.location.replace(LOGIN_URL);
    } catch (e) {
      // Service worker not ready, retry
      setTimeout(tryRedirect, 100);
    }
  }

  // Try immediately, then retry if service worker isn't ready
  tryRedirect();
})();
