import { describe, expect, it, vi, beforeEach } from 'vitest';
import type { RoleDTO } from '@effigenix/api-client';

vi.mock('../../utils/api-client.js', () => ({
  client: {
    roles: {
      list: vi.fn(),
    },
  },
}));

const { client } = await import('../../utils/api-client.js');

const mockRoles: RoleDTO[] = [
  { id: '1', name: 'ADMIN', permissions: [], description: 'Administrator' },
  { id: '2', name: 'SALES_MANAGER', permissions: [], description: 'Sales Manager' },
];

describe('useRoles – api-client integration', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('client.roles.list resolves with roles', async () => {
    vi.mocked(client.roles.list).mockResolvedValue(mockRoles);
    const result = await client.roles.list();
    expect(result).toEqual(mockRoles);
  });

  it('client.roles.list rejects with error', async () => {
    vi.mocked(client.roles.list).mockRejectedValue(new Error('Netzwerkfehler'));
    await expect(client.roles.list()).rejects.toThrow('Netzwerkfehler');
  });

  it('error message extraction from Error instance', () => {
    const err: unknown = new Error('Verbindungsfehler');
    const msg = err instanceof Error ? err.message : 'Unbekannter Fehler';
    expect(msg).toBe('Verbindungsfehler');
  });

  it('error message fallback for non-Error', () => {
    const err: unknown = 'string error';
    const msg = err instanceof Error ? err.message : 'Unbekannter Fehler';
    expect(msg).toBe('Unbekannter Fehler');
  });
});
