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()
}));

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

describe('Furniture App', () => {
  beforeEach(() => {
    vi.mocked(loadDashboard).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://furniture-display-demo.dream-views.com/availability',
      THALOS_DEFAULT_TENANT_ID: 'demo-tenant'
    };
    window.history.pushState({}, '', '/availability');
  });

  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 protected availability data', async () => {
    vi.mocked(getSessionMe).mockResolvedValue({
      isAuthenticated: true,
      subjectId: 'demo-user',
      tenantId: 'demo-tenant',
      provider: 0
    });
    vi.mocked(loadDashboard).mockResolvedValue({
      furnitureId: 'FURN-001',
      displayName: 'Chair',
      quantityAvailable: 4
    });

    render(<App />);

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

    await waitFor(() => {
      expect(loadDashboard).toHaveBeenCalledWith('FURN-001');
      expect(screen.getAllByText(/Chair/).length).toBeGreaterThan(0);
    });
  });

  it('allows creating local reservation records after loading availability', async () => {
    vi.mocked(getSessionMe).mockResolvedValue({
      isAuthenticated: true,
      subjectId: 'demo-user',
      tenantId: 'demo-tenant',
      provider: 0
    });
    vi.mocked(loadDashboard).mockResolvedValue({
      furnitureId: 'FURN-001',
      displayName: 'Chair',
      quantityAvailable: 4
    });

    render(<App />);
    await waitFor(() => expect(screen.getByRole('button', { name: 'Load Availability' })).toBeInTheDocument());
    fireEvent.click(screen.getByRole('button', { name: 'Load Availability' }));
    await waitFor(() => expect(screen.getAllByText('Chair').length).toBeGreaterThan(0));

    fireEvent.click(screen.getByText('Reservations'));
    fireEvent.change(screen.getByPlaceholderText('Customer name'), { target: { value: 'Jane Doe' } });
    fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '2' } });
    fireEvent.click(screen.getByRole('button', { name: 'Create Reservation' }));

    await waitFor(() => expect(screen.getByText('Jane Doe')).toBeInTheDocument());
  });
});
