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();
    window.__APP_CONFIG__ = {
      API_BASE_URL: 'http://localhost:8080',
      THALOS_AUTH_BASE_URL: 'https://auth.dream-views.com',
      THALOS_DEFAULT_RETURN_URL: 'https://waiter-floor-demo.dream-views.com/assignments',
      THALOS_DEFAULT_TENANT_ID: 'demo-tenant'
    };
    window.history.pushState({}, '', '/assignments');
  });

  it('shows central login action when session is missing', async () => {
    vi.mocked(getSessionMe).mockResolvedValue({ isAuthenticated: false, subjectId: '', tenantId: '', provider: 0 });

    render(<App />);

    await waitFor(() => expect(screen.getByRole('link', { name: 'Continue with Google' })).toBeInTheDocument());
    const link = screen.getByRole('link', { name: 'Continue with Google' }) as HTMLAnchorElement;
    expect(link.href).toContain('/api/identity/oidc/google/start');
    expect(link.href).toContain('tenantId=demo-tenant');
  });

  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.getByText('Submit Order')).toBeInTheDocument());
    fireEvent.click(screen.getByText('Submit Order'));
    fireEvent.change(screen.getByPlaceholderText('Order Id'), { target: { value: 'ORD-2200' } });
    fireEvent.click(screen.getByRole('button', { name: 'Submit Floor Order' }));

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