import { describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';
import ApiErrorBanner from './ApiErrorBanner.svelte';

describe('ApiErrorBanner', () => {
  test('renders error.message when present', () => {
    render(ApiErrorBanner, {
      props: {
        error: { code: 'server_error', message: 'database down', status: 500 },
        onRetry: () => {}
      }
    });
    expect(screen.getByRole('alert')).toHaveTextContent('database down');
  });

  test('falls back to generic text when error lacks message', () => {
    render(ApiErrorBanner, { props: { error: undefined, onRetry: () => {} } });
    expect(screen.getByRole('alert')).toHaveTextContent(/something went wrong/i);
  });

  test('clicking the button calls onRetry', async () => {
    const onRetry = vi.fn();
    render(ApiErrorBanner, {
      props: {
        error: { code: 'server_error', message: 'x', status: 500 },
        onRetry
      }
    });
    await fireEvent.click(screen.getByRole('button', { name: /try again/i }));
    expect(onRetry).toHaveBeenCalledTimes(1);
  });
});
