'use client';

import { useCallback, useEffect, useState } from 'react';
import type { HostDetail } from '@pac/types';
import { ApiError } from '@/lib/api-client';
import { hostApi } from './host-api';

export type LoadState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'ready'; data: HostDetail }
  | { status: 'error'; message: string; code?: number };

export function useHostAdmin() {
  const [state, setState] = useState<LoadState>({ status: 'idle' });

  const fetch = useCallback(async () => {
    setState({ status: 'loading' });
    try {
      const data = await hostApi.getSelf();
      setState({ status: 'ready', data });
    } catch (err) {
      if (err instanceof ApiError) {
        setState({ status: 'error', message: err.message, code: err.code });
      } else {
        setState({ status: 'error', message: err instanceof Error ? err.message : String(err) });
      }
    }
  }, []);

  useEffect(() => {
    void fetch();
  }, [fetch]);

  return { state, refresh: fetch };
}
