'use client'; import React, { createContext, useContext, useEffect, useState, useCallback } from 'react'; import { api } from '@/lib/api-client'; import { UserRole, UserStatus } from '@fileshare/shared'; export interface UserProfile { id: string; email: string; username: string; fullName: string; companyName?: string; role: UserRole; status: UserStatus; storageQuotaBytes: string; storageUsedBytes: string; canCreateShareLinks?: boolean; canDeleteFiles?: boolean; canViewOtherUsers?: boolean; } interface AuthContextType { user: UserProfile | null; isLoading: boolean; login: (identifier: string, password: string) => Promise; register: (data: { email: string; username: string; fullName: string; password: string; companyName?: string }) => Promise; logout: () => Promise; refreshProfile: () => Promise; isAdmin: boolean; isSuperAdmin: boolean; canViewOtherUsers: boolean; } const AuthContext = createContext(undefined); export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); const refreshProfile = useCallback(async () => { try { const profile = await api.get('/auth/me'); setUser(profile); } catch { setUser(null); } finally { setIsLoading(false); } }, []); useEffect(() => { refreshProfile(); }, [refreshProfile]); const login = async (identifier: string, password: string) => { const res: any = await api.post('/auth/login', { identifier, password }); if (res.accessToken) { api.setToken(res.accessToken); } setUser(res.user); }; const register = async (data: { email: string; username: string; fullName: string; password: string; companyName?: string }) => { const res: any = await api.post('/auth/register', data); if (res.accessToken) { api.setToken(res.accessToken); setUser(res.user); } return res; }; const logout = async () => { try { await api.post('/auth/logout', {}); } finally { api.setToken(null); setUser(null); window.location.href = '/login'; } }; const isSuperAdmin = user?.role === UserRole.SUPER_ADMIN; const isAdmin = user?.role === UserRole.ADMIN || isSuperAdmin; const canViewOtherUsers = isAdmin || !!user?.canViewOtherUsers; return ( {children} ); } export function useAuth() { const context = useContext(AuthContext); if (!context) { throw new Error('useAuth must be used within an AuthProvider'); } return context; }