import {
  getBasicAuthBasicStatus,
  peekBasicAuthSessionCredentials,
} from "@client/api/client";
import { useEffect, useState } from "react";

export type BasicAuthNavSession =
  | { kind: "inactive" }
  | { kind: "active"; username: string | null };

/** When Basic Auth is on, exposes the username from session storage for nav UI. */
export function useBasicAuthNavSession(): BasicAuthNavSession {
  const [state, setState] = useState<BasicAuthNavSession>({ kind: "inactive" });

  useEffect(() => {
    let cancelled = false;
    const run = async () => {
      try {
        const status = await getBasicAuthBasicStatus();
        if (cancelled) return;
        if (!status.basicAuthEnabled) {
          setState({ kind: "inactive" });
          return;
        }
        const creds = peekBasicAuthSessionCredentials();
        setState({ kind: "active", username: creds?.username ?? null });
      } catch {
        if (!cancelled) setState({ kind: "inactive" });
      }
    };
    void run();
    return () => {
      cancelled = true;
    };
  }, []);

  return state;
}
