import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';

import FeatureRequestsIndex from './Index';

vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));

vi.mock('@/Layouts/DashboardLayout', () => ({
  default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

vi.mock('@/Components/Shared/InertiaPagination', () => ({
  default: () => null,
}));

const makeRequest = (overrides = {}) => ({
  id: 'REQ0000000000000000000001',
  title: 'Dark mode support',
  description: 'Please add dark mode.',
  vote_count: 5,
  status: 'open' as const,
  user: { name: 'Alice' },
  created_at: '2026-01-01T00:00:00Z',
  ...overrides,
});

const baseProps = {
  feature_requests: {
    data: [makeRequest()],
    links: [],
    current_page: 1,
    last_page: 1,
    per_page: 20,
    total: 1,
  },
  voted_ids: [],
  status_filter: '',
  status_counts: {},
  my_request_ids: [],
  error: null,
};

describe('FE-ONERR-05 — handleVote onError', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('shows a toast on vote failure and does not indicate success', async () => {
    const { toast } = await import('sonner');
    const { router } = await import('@inertiajs/react');

    vi.mocked(router.post).mockImplementation((_url, _data, options) => {
      // Simulate a server error response
      const onError = (options as { onError?: (e: Record<string, string>) => void })?.onError;
      onError?.({});
    });

    render(<FeatureRequestsIndex {...baseProps} />);

    fireEvent.click(screen.getByRole('button', { name: 'Upvote Dark mode support' }));

    expect(toast.error).toHaveBeenCalledWith('Could not record your vote. Please try again.');
  });

  it('does not fire toast on successful vote', async () => {
    const { toast } = await import('sonner');
    const { router } = await import('@inertiajs/react');

    vi.mocked(router.post).mockImplementation(() => {
      // success path: no onError invoked
    });

    render(<FeatureRequestsIndex {...baseProps} />);

    fireEvent.click(screen.getByRole('button', { name: 'Upvote Dark mode support' }));

    expect(toast.error).not.toHaveBeenCalled();
  });
});
