import { useState, useCallback } from 'react';
import type { RoleDTO } from '@effigenix/api-client';
import { client } from '../utils/api-client.js';

interface RolesState {
  roles: RoleDTO[];
  loading: boolean;
  error: string | null;
}

function errorMessage(err: unknown): string {
  return err instanceof Error ? err.message : 'Unbekannter Fehler';
}

export function useRoles() {
  const [state, setState] = useState<RolesState>({
    roles: [],
    loading: false,
    error: null,
  });

  const fetchRoles = useCallback(async () => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const roles = await client.roles.list();
      setState({ roles, loading: false, error: null });
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
    }
  }, []);

  const clearError = useCallback(() => {
    setState((s) => ({ ...s, error: null }));
  }, []);

  return { ...state, fetchRoles, clearError };
}
