import {
  createContext,
  useContext,
  useMemo,
  type ReactNode,
} from 'react';

interface RepoContextValue {
  /** Project namespace (project name) */
  namespace: string | null;
  /** Repository name */
  repo: string | null;
  /** Full repo path: `{namespace}/{repo}` */
  repoPath: string | null;
  /** Whether both namespace and repo are available */
  isReady: boolean;
}

const RepoContext = createContext<RepoContextValue | null>(null);

interface RepoProviderProps {
  /** Project namespace (project name), typically from URL param */
  namespace: string | null;
  /** Repository name, typically from URL param */
  repo: string | null;
  children: ReactNode;
}

export function RepoProvider({ namespace, repo, children }: RepoProviderProps) {
  const value = useMemo<RepoContextValue>(() => ({
    namespace,
    repo,
    repoPath: namespace && repo ? `${namespace}/${repo}` : null,
    isReady: Boolean(namespace && repo),
  }), [namespace, repo]);

  return <RepoContext.Provider value={value}>{children}</RepoContext.Provider>;
}

export function useRepo() {
  const ctx = useContext(RepoContext);
  if (!ctx) throw new Error('useRepo must be used within RepoProvider');
  return ctx;
}
