import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'; import { supabase } from '../lib/supabase'; import type { Contact } from '../lib/types'; interface AuthState { contact: Contact | null; loading: boolean; /** Sign in with the admin's email + password (event-independent). */ signIn: (email: string, password: string) => Promise; signOut: () => Promise; } const AuthContext = createContext(null); // Load the current user's contact row. Returns null if it doesn't exist or the // contact is not an admin (this is an admin-only app). async function loadAdminContact(email: string): Promise { const { data } = await supabase .from('contacts') .select('*') .eq('email', email) .maybeSingle(); const c = data as Contact | null; return c && c.is_admin ? c : null; } export function AuthProvider({ children }: { children: ReactNode }) { const [contact, setContact] = useState(null); const [loading, setLoading] = useState(true); // On mount: restore any existing session and load the contact. If the // session belongs to a non-admin, sign out immediately (admin-only app). useEffect(() => { let cancelled = false; async function init() { const { data } = await supabase.auth.getSession(); const session = data.session; if (!session) { if (!cancelled) setLoading(false); return; } const c = session.user.email ? await loadAdminContact(session.user.email) : null; if (cancelled) return; if (c) { setContact(c); } else { // Not an admin — clear the session. await supabase.auth.signOut(); } setLoading(false); } init(); const { data: sub } = supabase.auth.onAuthStateChange(async (_event, session) => { if (!session) { setContact(null); return; } const c = session.user.email ? await loadAdminContact(session.user.email) : null; if (c) { setContact(c); } else { await supabase.auth.signOut(); setContact(null); } }); return () => { cancelled = true; sub.subscription.unsubscribe(); }; }, []); async function signIn(email: string, password: string) { const { data, error } = await supabase.auth.signInWithPassword({ email, password, }); if (error) throw new Error(error.message); const c = data.user.email ? await loadAdminContact(data.user.email) : null; if (!c) { // Signed in, but not an admin — reject and sign out. await supabase.auth.signOut(); throw new Error('This account is not an admin.'); } setContact(c); } async function signOut() { await supabase.auth.signOut(); setContact(null); } return ( {children} ); } export function useAuth(): AuthState { const ctx = useContext(AuthContext); if (!ctx) throw new Error('useAuth must be used within AuthProvider'); return ctx; }