// Supabase auth wrapper.
// Supports: email + password (primary), magic link, Google OAuth.
// Reads role from the `profiles` table (falls back to ADMIN_EMAILS list for bootstrap).

(function () {
  const cfg = window.SUPABASE_CONFIG || {};
  const isConfigured =
    !!cfg.url &&
    !!cfg.anonKey &&
    !cfg.url.startsWith("REPLACE_") &&
    !cfg.anonKey.startsWith("REPLACE_");

  const ADMIN_EMAILS_FALLBACK = (window.ADMIN_EMAILS || []).map((e) => e.toLowerCase());

  let supabase = null;
  if (isConfigured && window.supabase && window.supabase.createClient) {
    supabase = window.supabase.createClient(cfg.url, cfg.anonKey, {
      auth: { persistSession: true, autoRefreshToken: true, detectSessionInUrl: true },
    });
  }

  async function fetchProfile(userId) {
    if (!supabase || !userId) return null;
    const { data, error } = await supabase
      .from("profiles")
      .select("id, email, full_name, avatar_url, role")
      .eq("id", userId)
      .maybeSingle();
    if (error) {
      console.warn("[auth] profile fetch error:", error.message);
      return null;
    }
    return data;
  }

  function useAuth() {
    const [session, setSession] = React.useState(null);
    const [profile, setProfile] = React.useState(null);
    const [loading, setLoading] = React.useState(true);

    React.useEffect(() => {
      if (!supabase) {
        setLoading(false);
        return;
      }
      let mounted = true;
      supabase.auth.getSession().then(async ({ data }) => {
        if (!mounted) return;
        setSession(data.session || null);
        if (data.session?.user) {
          setProfile(await fetchProfile(data.session.user.id));
        }
        setLoading(false);
      });
      const { data: sub } = supabase.auth.onAuthStateChange(async (_event, s) => {
        if (!mounted) return;
        setSession(s || null);
        if (s?.user) {
          setProfile(await fetchProfile(s.user.id));
        } else {
          setProfile(null);
        }
      });
      return () => {
        mounted = false;
        sub.subscription.unsubscribe();
      };
    }, []);

    const user = session?.user || null;
    const email = user?.email?.toLowerCase() || null;

    // Role priority: profiles.role (DB) > ADMIN_EMAILS bootstrap list > "viewer"
    const dbRole = profile?.role;
    const fallbackAdmin = !!email && ADMIN_EMAILS_FALLBACK.includes(email);
    // Normalise legacy "user" → "viewer"
    const rawRole = !user ? "guest" : (dbRole === "user" ? "viewer" : (dbRole || (fallbackAdmin ? "admin" : "viewer")));
    const role = rawRole;

    // Role level for hierarchy checks (mirrors public.role_level in DB)
    const ROLE_LEVEL = { admin: 100, hr_manager: 60, recruiter: 40, viewer: 10, user: 10, guest: 0 };
    const lvl = ROLE_LEVEL[role] ?? 0;
    const isAdmin       = role === "admin";
    const isHrManager   = role === "hr_manager";
    const canEdit         = lvl >= ROLE_LEVEL.recruiter;   // recruiter+
    const canManageUsers  = lvl >= ROLE_LEVEL.hr_manager;  // hr_manager+
    const canDelete       = lvl >= ROLE_LEVEL.hr_manager;  // hr_manager+
    const canAccessSettings = isAdmin;

    const perms = {
      isAdmin, isHrManager,
      canEdit, canDelete, canManageUsers, canAccessSettings,
      role, level: lvl,
    };

    const signInWithGoogle = async () => {
      if (!supabase) return { error: { message: "Supabase ยังไม่ตั้งค่า" } };
      return supabase.auth.signInWithOAuth({
        provider: "google",
        options: { redirectTo: window.location.origin + window.location.pathname },
      });
    };

    const signInWithPassword = async (email, password) => {
      if (!supabase) return { error: { message: "Supabase ยังไม่ตั้งค่า" } };
      const { data, error } = await supabase.auth.signInWithPassword({ email, password });
      return { data, error };
    };

    const signUpWithPassword = async (email, password, fullName) => {
      if (!supabase) return { error: { message: "Supabase ยังไม่ตั้งค่า" } };
      const { data, error } = await supabase.auth.signUp({
        email,
        password,
        options: {
          data: { full_name: fullName || null },
          emailRedirectTo: window.location.origin + window.location.pathname,
        },
      });
      return { data, error };
    };

    const signInWithMagicLink = async (email) => {
      if (!supabase) return { error: { message: "Supabase ยังไม่ตั้งค่า" } };
      const { data, error } = await supabase.auth.signInWithOtp({
        email,
        options: { emailRedirectTo: window.location.origin + window.location.pathname },
      });
      return { data, error };
    };

    const sendPasswordReset = async (email) => {
      if (!supabase) return { error: { message: "Supabase ยังไม่ตั้งค่า" } };
      return supabase.auth.resetPasswordForEmail(email, {
        redirectTo: window.location.origin + window.location.pathname,
      });
    };

    const signOut = async () => {
      if (!supabase) return;
      await supabase.auth.signOut();
      setSession(null);
      setProfile(null);
    };

    // -------- Admin RPC helpers --------
    const listUsers = async () => {
      if (!supabase) return { error: { message: "Supabase ยังไม่ตั้งค่า" } };
      return supabase.rpc("admin_list_users");
    };
    const setUserRole = async (targetUserId, newRole) => {
      if (!supabase) return { error: { message: "Supabase ยังไม่ตั้งค่า" } };
      return supabase.rpc("admin_set_role", { target_user_id: targetUserId, new_role: newRole });
    };
    const deleteUser = async (targetUserId) => {
      if (!supabase) return { error: { message: "Supabase ยังไม่ตั้งค่า" } };
      return supabase.rpc("admin_delete_user", { target_user_id: targetUserId });
    };

    return {
      user,
      profile,
      session,
      loading,
      isAdmin,
      role,
      perms,
      isConfigured,
      signInWithGoogle,
      signInWithPassword,
      signUpWithPassword,
      signInWithMagicLink,
      sendPasswordReset,
      signOut,
      listUsers,
      setUserRole,
      deleteUser,
    };
  }

  window.AUTH = { useAuth, supabase, isConfigured };
})();
