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, loginSession } from './api/sessionApi';
import App from './App';

describe('Thalos App', () => {
  beforeEach(() => {
    vi.mocked(loadDashboard).mockReset();
    vi.mocked(getSessionMe).mockReset();
    vi.mocked(loginSession).mockReset();
  });

  it('renders login gate and signs in through Thalos session endpoint', async () => {
    vi.mocked(getSessionMe)
      .mockResolvedValueOnce({ isAuthenticated: false, subjectId: '', tenantId: '', provider: 0 })
      .mockResolvedValueOnce({ isAuthenticated: true, subjectId: 'demo-user', tenantId: 'demo-tenant', provider: 0 });

    render(<App />);

    await waitFor(() => expect(screen.getByRole('button', { name: 'Sign In' })).toBeInTheDocument());

    fireEvent.change(screen.getByLabelText('Subject Id'), { target: { value: 'alice' } });
    fireEvent.click(screen.getByRole('button', { name: 'Sign In' }));

    await waitFor(() => {
      expect(loginSession).toHaveBeenCalledTimes(1);
      expect(screen.getByText(/subject: demo-user/i)).toBeInTheDocument();
    });
  });

  it('loads protected session snapshot through dashboard adapter', async () => {
    vi.mocked(getSessionMe).mockResolvedValue({
      isAuthenticated: true,
      subjectId: 'demo-user',
      tenantId: 'demo-tenant',
      provider: 0
    });
    vi.mocked(loadDashboard).mockResolvedValue({
      isAuthenticated: true,
      subjectId: 'demo-user',
      tenantId: 'demo-tenant',
      provider: 0
    });

    render(<App />);

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

    await waitFor(() => {
      expect(loadDashboard).toHaveBeenCalledTimes(1);
      expect(screen.getByText(/demo-user/)).toBeInTheDocument();
    });
  });
});
