import { render, screen, waitFor } from '@testing-library/react'

import UnionLogin from './UnionLogin'

const logoutMock = jest.fn()

jest.mock('@tidbcloud/uikit', () => ({
  Typography: ({ children }: { children?: any }) => <div>{children}</div>
}))

jest.mock('dbaas/components/Error', () => ({
  ErrorPanel: ({ message, children }: { message?: string; children?: any }) => (
    <div>
      <div>{message}</div>
      {children}
    </div>
  )
}))

jest.mock('dbaas/components/Placeholder', () => ({
  __esModule: true,
  default: () => <div>loading</div>
}))

jest.mock('../../../config', () => ({
  __esModule: true,
  default: {
    UNION_LAKE_REDIRECT_ORIGINS: ['https://lake.tidbcloud.com']
  }
}))

jest.mock('dbaas/services/auth', () => ({
  __esModule: true,
  default: {
    logout: (...args: unknown[]) => logoutMock(...args)
  }
}))

describe('UnionLogin', () => {
  beforeEach(() => {
    logoutMock.mockReset()
  })

  test('calls auth logout with the sanitized sign-in redirect', async () => {
    window.history.pushState(
      {},
      '',
      '/union/login?returnTo=lake&redirectUri=https%3A%2F%2Flake.tidbcloud.com%2Fwelcome%3Ftab%3Doverview'
    )

    render(<UnionLogin />)

    await waitFor(() => {
      expect(logoutMock).toHaveBeenCalledWith(
        '/signin?returnTo=lake&redirectUri=https%3A%2F%2Flake.tidbcloud.com%2Fwelcome%3Ftab%3Doverview',
        false
      )
    })

    expect(screen.getByTestId('union-login-page')).toBeTruthy()
  })

  test('shows an error and does not trigger logout for invalid params', () => {
    window.history.pushState({}, '', '/union/login?returnTo=lake&redirectUri=https%3A%2F%2Fevil.example.com%2Fwelcome')

    render(<UnionLogin />)

    expect(logoutMock).not.toHaveBeenCalled()
    expect(screen.getByText('Invalid login link.')).toBeTruthy()
    expect(screen.getByText('Disallowed union login redirect URI.')).toBeTruthy()
  })
})
