import type { AdminSessionResponse } from "@xtablo/shared-types";
import { useEffect, useState } from "react";
import {
  clearStoredAdminSession,
  getStoredAdminSession,
  type StoredAdminSession,
  storeAdminSession,
} from "../lib/adminSession";
import { adminApi } from "../lib/api";

export function useAdminSession() {
  const [session, setSession] = useState<StoredAdminSession | null>(() => getStoredAdminSession());
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    setSession(getStoredAdminSession());
  }, []);

  const unlock = async (accessToken: string) => {
    setIsPending(true);
    setError(null);

    try {
      const response = await adminApi.post<AdminSessionResponse>("/admin/auth/exchange", {
        accessToken,
      });

      storeAdminSession(response.data);
      setSession(response.data);
      return response.data;
    } catch {
      clearStoredAdminSession();
      setSession(null);
      setError("Invalid privileged access token");
      return null;
    } finally {
      setIsPending(false);
    }
  };

  const logout = () => {
    clearStoredAdminSession();
    setSession(null);
  };

  return {
    error,
    isAuthenticated: session !== null,
    isPending,
    logout,
    operatorEmail: session?.operatorEmail ?? null,
    role: session?.role ?? null,
    session,
    unlock,
  };
}
