import { createContext, useContext, ReactNode } from 'react';
import { useAuthStore } from '@/stores/auth.store';
import { isAdmin } from '@/utils/roles';

interface MediaAuthState {
  isAuthenticated: boolean;
  isApproved: boolean; // True if NOT a USER or TEMP role
  user: {
    id: string;
    email: string;
    role: string;
  } | null;
  token: string | null;
}

interface MediaAuthContextValue extends MediaAuthState {
  checkAuth: () => void;
}

const MediaAuthContext = createContext<MediaAuthContextValue | undefined>(undefined);

export function useMediaAuth() {
  const context = useContext(MediaAuthContext);
  if (!context) {
    throw new Error('useMediaAuth must be used within MediaAuthProvider');
  }
  return context;
}

interface MediaAuthProviderProps {
  children: ReactNode;
}

export function MediaAuthProvider({ children }: MediaAuthProviderProps) {
  // Read auth state directly from the Zustand auth store (single source of truth)
  const authUser = useAuthStore((s) => s.user);
  const accessToken = useAuthStore((s) => s.accessToken);
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const hydrate = useAuthStore((s) => s.hydrate);

  // Approved means user has an admin role (admins can chat)
  const isApproved = isAuthenticated && !!authUser && isAdmin(authUser);

  const user = authUser
    ? { id: authUser.id, email: authUser.email, role: authUser.role }
    : null;

  const checkAuth = () => {
    // Re-hydrate from persisted storage
    hydrate();
  };

  const value: MediaAuthContextValue = {
    isAuthenticated,
    isApproved,
    user,
    token: accessToken,
    checkAuth,
  };

  return (
    <MediaAuthContext.Provider value={value}>
      {children}
    </MediaAuthContext.Provider>
  );
}
