import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';

import { rest } from 'msw';
import { setupServer } from 'msw/node';

import Login from 'src/pages/authentication/Login';
import { render, screen } from 'src/utils/test';

const INSTANCE_1 = { id: 1, name: 'comu1' };
const INSTANCE_2 = { id: 2, name: 'comu2' };

const server = setupServer(
  rest.get(/\/auth\/instances/, (req, res, ctx) => {
    let instances: Array<typeof INSTANCE_1> = [];
    switch (req.url.searchParams.get('username')) {
      case '1111':
        instances = [INSTANCE_1];
        break;
      case '2222':
        instances = [INSTANCE_1, INSTANCE_2];
        break;
      default:
        break;
    }
    return res(ctx.json(instances));
  }),
);

describe('Login', () => {
  beforeAll(() => {
    server.listen();
  });
  afterEach(() => server.resetHandlers());
  afterAll(() => server.close());

  test("doesn't have password input", async () => {
    render(<Login />);

    expect(screen.queryByText('Contraseña')).not.toBeInTheDocument();
  });

  test('shows password input after username is entered', async () => {
    render(<Login />);

    await userEvent.type(screen.getByLabelText('Usuario'), '1111');
    await userEvent.click(screen.getByText('Continuar'));
    expect(await screen.findByLabelText('Contraseña')).toBeInTheDocument();
  });

  test("doesn't continue if no username entered", async () => {
    render(<Login />);

    await userEvent.click(screen.getByText('Continuar'));
    expect(
      await screen.findByText('Este campo es obligatorio'),
    ).toBeInTheDocument();
    expect(screen.queryByText('Contraseña')).not.toBeInTheDocument();
  });

  test('selects single community', async () => {
    render(<Login />);

    await userEvent.type(screen.getByLabelText('Usuario'), '1111');
    await userEvent.click(screen.getByText('Continuar'));
    expect(await screen.findByText('comu1')).toBeInTheDocument();
    expect(screen.getByLabelText('Usuario')).toBeDisabled();
  });

  test('shows communities modal', async () => {
    render(<Login />);

    await userEvent.type(screen.getByLabelText('Usuario'), '2222');
    await userEvent.click(screen.getByText('Continuar'));
    expect(
      await screen.findByText('Seleccionar una comunidad'),
    ).toBeInTheDocument();
    expect(await screen.findByText('comu1')).toBeInTheDocument();
    expect(await screen.findByText('comu2')).toBeInTheDocument();
  });
});
