// ===== Supabase Auth client =====
// SUPABASE_URL and SUPABASE_ANON_KEY are injected by Cloudflare Pages
// via the /api/config endpoint to avoid hardcoding in static files.

window.MEI_AUTH = (() => {
  let _client = null;
  let _config = null;

  async function getConfig() {
    if (_config) return _config;
    const r = await fetch("/api/config");
    if (!r.ok) throw new Error("Cannot load auth config");
    _config = await r.json();
    return _config;
  }

  // Load supabase-js from CDN and initialise client
  async function getClient() {
    if (_client) return _client;
    const cfg = await getConfig();

    // Dynamically load supabase-js if not already loaded
    if (!window.supabase) {
      await new Promise((resolve, reject) => {
        const s = document.createElement("script");
        s.src = "https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/dist/umd/supabase.min.js";
        s.onload = resolve;
        s.onerror = reject;
        document.head.appendChild(s);
      });
    }

    _client = window.supabase.createClient(cfg.supabaseUrl, cfg.supabaseAnonKey, {
      auth: {
        persistSession: true,
        autoRefreshToken: true,
        detectSessionInUrl: true,
      },
    });
    return _client;
  }

  return {
    getClient,

    // Sign in with email + password
    async signInWithPassword(email, password) {
      const sb = await getClient();
      const { error } = await sb.auth.signInWithPassword({ email, password });
      if (error) throw new Error(error.message);
    },

    // Send Magic Link to email
    async sendMagicLink(email) {
      const sb = await getClient();
      const { error } = await sb.auth.signInWithOtp({
        email,
        options: { shouldCreateUser: false }, // only pre-existing users can login
      });
      if (error) throw new Error(error.message);
    },

    // Get current session (null if not logged in)
    async getSession() {
      const sb = await getClient();
      const { data: { session } } = await sb.auth.getSession();
      return session;
    },

    // Get current user
    async getUser() {
      const sb = await getClient();
      const { data: { user } } = await sb.auth.getUser();
      return user;
    },

    // Subscribe to auth state changes
    async onAuthStateChange(callback) {
      const sb = await getClient();
      return sb.auth.onAuthStateChange(callback);
    },

    // Change password for the currently logged-in user
    async updatePassword(newPassword) {
      const sb = await getClient();
      const { error } = await sb.auth.updateUser({ password: newPassword });
      if (error) throw new Error(error.message);
    },

    // Logout
    async signOut() {
      const sb = await getClient();
      await sb.auth.signOut();
    },

    // Get access token for API calls
    async getAccessToken() {
      const session = await this.getSession();
      return session?.access_token || null;
    },
  };
})();
