import { useQuery } from "@tanstack/react-query";
import { User } from "@shared/schema";

// For the demo, we're setting a fixed user ID
// In production, this would come from an auth provider/session
const CURRENT_USER_ID = 1; // Using admin user for demo

export type UserRole = "user" | "contributor" | "reviewer" | "editor" | "admin";

interface AuthUser {
  id: number;
  displayName: string | null;
  username: string;
  email: string;
  role: UserRole;
  avatar: string | null;
}

export function useAuth() {
  const { data: user, isLoading, error } = useQuery<Omit<User, "password">>({
    queryKey: [`/api/users/${CURRENT_USER_ID}`],
  });

  const isAuthenticated = !!user;
  
  // Check if user has any of the specified roles
  const hasRole = (roles: UserRole | UserRole[]): boolean => {
    if (!user) return false;
    
    const rolesToCheck = Array.isArray(roles) ? roles : [roles];
    return rolesToCheck.includes(user.role as UserRole);
  };

  // Role-specific checks
  const isAdmin = user?.role === "admin";
  const isEditor = hasRole(["admin", "editor"]);
  const isReviewer = hasRole(["admin", "editor", "reviewer"]);
  const isContributor = hasRole(["admin", "editor", "reviewer", "contributor"]);

  // Access control for editorial features
  const canManageUsers = isAdmin;
  const canManageContent = isEditor;
  const canReviewContent = isReviewer;
  const canCreateContent = isContributor;
  
  // Check if user can access dashboard
  const canAccessDashboard = isContributor;

  return {
    user: user as AuthUser | undefined,
    isLoading,
    isAuthenticated,
    error,
    hasRole,
    isAdmin,
    isEditor,
    isReviewer,
    isContributor,
    canManageUsers,
    canManageContent,
    canReviewContent,
    canCreateContent,
    canAccessDashboard,
    currentUserId: CURRENT_USER_ID
  };
}
