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

vi.mock('./api/sessionApi', () => ({
  getSessionMe: vi.fn(),
  loginSession: vi.fn(),
  refreshSession: vi.fn(),
  logoutSession: vi.fn()
}));

vi.mock('./api/dashboardApi', () => ({
  loadDashboard: vi.fn(),
  submitFloorOrder: vi.fn()
}));

import { loadDashboard, submitFloorOrder } from './api/dashboardApi';
import { getSessionMe } from './api/sessionApi';
import App from './App';

describe('Waiter Floor App', () => {
  beforeEach(() => {
    vi.mocked(loadDashboard).mockReset();
    vi.mocked(submitFloorOrder).mockReset();
    vi.mocked(getSessionMe).mockReset();
  });

  it('loads assignments for authenticated users', async () => {
    vi.mocked(getSessionMe).mockResolvedValue({
      isAuthenticated: true,
      subjectId: 'demo-user',
      tenantId: 'demo-tenant',
      provider: 0
    });
    vi.mocked(loadDashboard).mockResolvedValue({ contextId: 'demo-context', summary: 'assigned' });

    render(<App />);

    await waitFor(() => expect(screen.getByRole('button', { name: 'Load Assignments' })).toBeInTheDocument());
    fireEvent.click(screen.getByRole('button', { name: 'Load Assignments' }));

    await waitFor(() => expect(loadDashboard).toHaveBeenCalledWith('demo-context'));
  });

  it('submits floor orders from action route', async () => {
    vi.mocked(getSessionMe).mockResolvedValue({
      isAuthenticated: true,
      subjectId: 'demo-user',
      tenantId: 'demo-tenant',
      provider: 0
    });
    vi.mocked(submitFloorOrder).mockResolvedValue({ orderId: 'ORD-1001', accepted: true, message: 'ok' });

    render(<App />);

    await waitFor(() => expect(screen.getByRole('button', { name: 'Submit Order' })).toBeInTheDocument());
    fireEvent.click(screen.getByRole('button', { name: 'Submit Order' }));
    fireEvent.click(screen.getByRole('button', { name: 'Submit Floor Order' }));

    await waitFor(() => expect(submitFloorOrder).toHaveBeenCalledTimes(1));
  });
});
