import { create } from 'zustand' import type { UserRole } from '../data/AdminUserRepository' import { supabase } from '../data/supabaseClient' export type { UserRole } interface AuthStoreState { userId: string | null username: string | null role: UserRole | null /** Lets a specific Admin post/retire site-wide announcements without the * whole Admin role gaining that ability — a Super Admin can always post * regardless of this flag (see can_manage_announcements() in the DB). */ canPostAnnouncements: boolean isLoaded: boolean /** One-time fetch of your own profile — nothing else in the app changes * your own username while you're signed in, and your own role changing * (a Super-Admin-only action on someone else's account, see * organized-ideas.md §6) isn't something you'd do to yourself, so * there's no need to keep this live. */ load: () => Promise } export const useAuthStore = create((set) => ({ userId: null, username: null, role: null, canPostAnnouncements: false, isLoaded: false, load: async () => { const { data: { user }, } = await supabase.auth.getUser() if (!user) { set({ isLoaded: true }) return } const { data } = await supabase .from('profiles') .select('username, role, can_post_announcements') .eq('id', user.id) .single() set({ userId: user.id, username: data?.username ?? null, role: (data?.role as UserRole | undefined) ?? null, canPostAnnouncements: data?.can_post_announcements ?? false, isLoaded: true, }) }, }))